繁体   English   中英

异步/等待在我的示例中不起作用

[英]Async/Await doesn't work in my example

许多JavaScript开发人员都知道async/await及其好处,因此我尝试测试一个异步操作的旧示例,让我们看一下我的实验:

无疑,以下代码的答案是:

/*Line: 1*/ console.log(`1`);
/*Line: 2*/ console.log(`2`);
/*Line: 3*/ console.log(`3`);

//==>  123

所以我想在第二行输入setTimeout

/*Line: 1*/ console.log(`1`);
/*Line: 2*/ setTimeout(() => {
               console.log(`2`);
            }, 0);
/*Line: 3*/ console.log(`3`);

//==> 132

由于第二行的异步作用,因此213 ,因此在控制台132中显示。

我决定使用新JavaScript async/await功能再次查看123 ,因此我编写了上面的代码,如下所示:

(async () => {
    console.log(`1`);
    await setTimeout(() => {
        console.log(`2`);
    }, 0);
    console.log(`3`);
})();

但这不起作用,我再次在控制台中看到132 我哪部分做错了或不知道?

await等待诺言解决。 由于setTimeout不是一个承诺,因此程序的执行不会等到执行完毕。 您需要按照以下链接的第一个示例中的指定将setTimeout()包装在promise中,以使示例按预期工作:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

setTimeout没有返回承诺。 为了使其正常工作,您将必须创建一个函数,该函数返回在setTimeout回调内部解析的Promise。

 (async () => { console.log(`1`); await new Promise(resolve => { setTimeout(() => { resolve('resolved'); console.log(`2`); },0); }); console.log(`3`); })(); 

您只能等待返回承诺的函数。 请注意,await只能在异步函数内使用:

 async function someFunc() { console.log(`1`); await new Promise((resolve, reject) => setTimeout(() => { console.log(`2`); resolve(); }, 0)); console.log(`3`); } someFunc(); 

应该在返回promise的函数上调用Await(否则它将返回)。

setTimeout不返回承诺,因此应使用返回承诺的函数将其包装。

在此处阅读有关此内容的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

此代码应能完成工作。

 (async() => { console.log(`1`); await (() => { return new Promise( resolve => { setTimeout(() => { console.log(2); resolve() }, 1000); }); })(); console.log(`3`); })(); 

您需要创建函数,例如async function foo() {} ,并在其中进行await调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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