简体   繁体   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;

Why do we see the following scenario? 为什么我们会看到以下情况?

  1. Entering the f1. 输入f1。 Stops on await. 停止等待。
  2. Returns from f1 (console.log(x) command doesn't execute) 从f1返回(console.log(x)命令不执行)
  3. assign 3 to x (ERROR! await skipped, js steps forward) 将3分配给x(错误!等待跳过,js前进)
  4. Return to f1 on line "console.log(x)". 返回到“console.log(x)”行的f1。 Print x. 打印x。

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.

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