-1

I want the hello function to return a Promise. Why does it return undefined?

I think the wait function is confusing me. I tried to explain my understanding of it but could not put it in words.

Could someone please explain this to me in very basic terms.

    function wait (ms =0){
    return new Promise((resolve)=>{
    setTimeout(resolve, ms)
    })
    }

      async function hello(){
     const nw = await wait(2000);
     console.log(nw);
     }


hello();
Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17
delaka
  • 1
  • `wait` returns a promise. But as you are `await`ing the promise, `nw` is the result of the promise -- in your case `undefined` because you call `resolve` without any parameter -- and not the promise itself. – derpirscher Oct 10 '20 at 10:55
  • Can you please explain the wait function for me. I know how arrow functions work but this is really confusing me. – delaka Oct 10 '20 at 11:00
  • So what's the actual question here? How [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)s work? How [`async`/`await`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) works? – Andreas Oct 10 '20 at 11:03
  • Does this question help? https://stackoverflow.com/questions/39458201/understanding-javascript-promise-object – Charlie Wallace Oct 10 '20 at 14:35

2 Answers2

1

Unless you resolve with an argument you get nothing. You want:

setTimeout(() => { resolve('hello') }, ms);

The key here is setTimeout() does not give any argument to the function you give it, it just runs it at that time. In this case it's the same as:

// Wait ms milliseconds
resolve();
tadman
  • 208,517
  • 23
  • 234
  • 262
0

Your wait function returns a promise. But as you are awaiting it, nw is the result of the promise -- in your case undefined because you call resolve without any parameter -- and not the promise itself.

Your code is (more or less) the same as this


function wait (ms = 0){
  return new Promise((resolve) => {
    setTimeout(() => { resolve(); }, ms)  //Resolve the promise after the given time
  });
}

function hello() {
  wait(2000)
    .then((result) => {
      const nw = result;
      console.log(nw);
    })
   
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35