[英]Await doesn't wait
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x);
}
f1();
let x = 3;
为什么我们会看到以下情况?
为什么JS不等待等待并向前迈进? 你可以给我一个建议吗?
f1
是异步的(等待仅发生在该异步上下文中)。 因此,执行f1(),因为它是异步的,所以let x = 3;
行无需等待即可立即执行。
如果你还在await
对f1()的调用,它应该做你期望的事情。 但是,为了使用await,必须将该代码包装在另一个异步函数中,然后执行该函数。
演示(无需等待):
function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); } f1(); let x = 3; console.log(x);
工作版(额外等待):
function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); } async function f2() { await f1(); let x = 3; console.log(x); }; f2();
更简单
(async function() { function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); } await f1(); let x = 3; console.log(x); })();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.