为什么在我的情况下`async/await'不起作用? [英] Why `async/await` doesn't work in my case?

查看:2216
本文介绍了为什么在我的情况下`async/await'不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关async/await的信息,但我有一个关键问题. 首先,我解释一个古老的例子来说明问题的基础,然后再问确切的问题.

I read about async/await, but I've a critical question. At first I explain an old example to show base of my question and then I ask my exact question.

每个人都知道:

console.log('1');
console.log('2');
console.log('3'); // Ex: 123

这很简单,但在以下情况下:

It is simple but in below case:

console.log('1');
setTimeout(()=>{
    console.log('2');
},0);
console.log('3'); // Ex: 132

这也很简单,setTimeout函数是asynchronous,而JavaScript从其跳转并在解析运行其函数之后,因此我们看到213之后.

It is simple too, setTimeout function is asynchronous and JavaScript jump from it and after resolve run its function, so we see 2 after 1 and 3.

但是,现在我读了async/await,并编写了这样的函数:

But, now I read async/await and I wrote a function like this:

(async function test() {
    console.log('1');
    await setTimeout(()=>{
        console.log('2');
    },0);
    console.log('3');
})(); // Ex: 132

导出也是132,为什么?这是我的问题,为什么32之前运行?我期望由于1之后的async/await JavaScript等待2然后写3.为什么132?

The Export is 132 too, why? this is my question, why 3 run before 2? I expect because of async/await after 1 JavaScript wait for 2 and then wrote 3. why 132?

推荐答案

await仅在传递给它的值为Promise时挂起.对于您来说,setTimeout返回一个Number,所以await不会等待它.

await only suspends when the value passed to it is a Promise. In your case, setTimeout returns a Number so await doesn't wait for it.

正确的代码如下:

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

这篇关于为什么在我的情况下`async/await'不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆