下面的代码按预期每秒记录一次“ hello world”。
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();
}
考虑到函数的return
值async
对应resolve
于promise中函数返回的值,为什么下面的代码不能输出相同的结果,而是立即记录所有“ hello world”:
async function moveOneStepAsync() {
setTimeout(() => {
return console.log('Hello world!');
}, 1000);
}
async function main() {
await moveOneStepAsync();
await moveOneStepAsync();
await moveOneStepAsync();
await moveOneStepAsync();
}
那是因为在您的函数setTimeout
中不返回承诺。setTimeout本身将同步执行。它在事件循环中添加了作为参数传递的回调,以便在提及的时间及时执行。await
main
同样在此代码中,回调的返回并不意味着回调将在1秒钟内运行,并且返回的值将无处可寻。
async
关键字告诉您函数会返回promise,并且其中可能包含功能await
强大的代码。因此,由于您的代码中没有等待,因此它看起来像
function moveOneStepAsync() {
setTimeout(() => {
return console.log('Hello world!');
}, 1000);
return Promise.resolve();
}
因此,您await
的主用户将等待一个事件循环跳动,转到下一个“步骤”
阅读有关setTimeout,事件循环以及希望进一步了解的内容
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句