[英]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;
Why do we see the following scenario? 为什么我们会看到以下情况?
Why JS not waiting on await and steps forward? 为什么JS不等待等待并向前迈进? May you give me an advice?
你可以给我一个建议吗?
f1
is asynchronous (the await only occurs within that asynchronous context). f1
是异步的(等待仅发生在该异步上下文中)。 Therefore, f1() is executed, and because it's async, the let x = 3;
因此,执行f1(),因为它是异步的,所以
let x = 3;
line executes immediately without waiting. 行无需等待即可立即执行。
If you also await
the call to f1(), it should do what you're expecting. 如果你还在
await
对f1()的调用,它应该做你期望的事情。 However in order to use await, you must wrap that code inside another async function, and then execute that function. 但是,为了使用await,必须将该代码包装在另一个异步函数中,然后执行该函数。
Demo (no 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);
Working version (with extra await): 工作版(额外等待):
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();
More simpler 更简单
(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.