【发布时间】:2021-11-25 22:00:25
【问题描述】:
我对 async/await 做了一些研究,但我很困惑。它说 async/await 是非阻塞的。我研究了 developer.mozilla.org 异步函数示例。 参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
//uncomment this code to see promise result
//resolveAfter2Seconds().then(result=>{
//console.log(result);
//});
console.log('calling end');
}
asyncCall();
async/await 结果是
> "calling"
> "resolved"
> "calling end"
但承诺结果是
> "calling"
> "calling end"
> "resolved"
所以如果 async/await 是非阻塞的,那么为什么它不会在“解决”之前控制台“调用结束”??
【问题讨论】:
-
await没有阻塞。它允许编写异步代码,如同步代码,并按照编写顺序执行行,同时是非阻塞的(超时、间隔、HTTP 请求等仍然同时运行)。.then()根本不这样做。.then()中的内容不会在写入时执行,而是稍后执行。您的示例有缺陷,两个代码不等效,这就是您得到两个不同结果的原因。 -
@zhulien 能否提供一些博客或文档参考资料,我将在其中进行更详细的研究?