Skip to content Skip to sidebar Skip to footer

Writing Async/await Version Of A Promise

The code below logs 'hello world' once in a second as expected. function moveOneStep() { return new Promise((res, rej) => { setTimeout(() => { res(console.log('H

Solution 1:

That's because setTimeout does not return promise to await it in your main function. setTimeout itself executes synchronously. It adds to an event loop the callback that is passed as an argument to execute in time that is mentioned.

Also in this code return of your callback means nothing as callback with be run in 1 sec and the returned value will go nowhere.

async keyword tells you that functions returns promise and could have awaitable code in it. So as there is not await in your code it then looks like

functionmoveOneStepAsync() {
  setTimeout(() => {
    returnconsole.log('Hello world!');
  }, 1000);
  returnPromise.resolve();
}

So your await in main will await one event loop tick to go to the next "step"

Read about setTimeout, event loop, and what await expects to understand it more in-depth

Solution 2:

You do not return anything to the function, you return back to the internal setTimeout function, and that does not do anything with that value. Calling setTimeout does not return a promise, it rather returns a timer immeadiately. And therefore all the moveOneStepAsync calls execute immeadiately, the timers get set, and fire after one second.

Post a Comment for "Writing Async/await Version Of A Promise"