繁体   English   中英

等待不等

[英]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;

为什么我们会看到以下情况?

  1. 输入f1。 停止等待。
  2. 从f1返回(console.log(x)命令不执行)
  3. 将3分配给x(错误!等待跳过,js前进)
  4. 返回到“console.log(x)”行的f1。 打印x。

为什么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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM