Writing async/await version of a promise

ぐ巨炮叔叔 提交于 2020-01-04 11:55:33

问题


The code below logs 'hello world' once in a second as expected.

function moveOneStep() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res(console.log('Hello world!'))
    }, 1000)
  })  
}

async function main() {
  await moveOneStep();
  await moveOneStep();
  await moveOneStep();
  await moveOneStep();
}

Considering the return value of an async function corresponds to what is returned from resolve function in promises, why doesn't the code below output the same result, but instead logs all the 'hello world's at once:

async function moveOneStepAsync() {
  setTimeout(() => {
    return console.log('Hello world!');
  }, 1000);
}

async function main() {
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
  await moveOneStepAsync();
}

回答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

function moveOneStepAsync() {
  setTimeout(() => {
    return console.log('Hello world!');
  }, 1000);
  return Promise.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




回答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.



来源:https://stackoverflow.com/questions/54206147/writing-async-await-version-of-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!