问题
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 await
able 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