为什么`async/await`在我的情况下不起作用?

4 javascript asynchronous async-await ecmascript-2017

我读到了async/await,但我有一个关键问题.首先,我解释一个旧的例子,以显示我的问题的基础,然后我问我的确切问题.

大家都知道:

console.log('1');
console.log('2');
console.log('3'); // Ex: 123
Run Code Online (Sandbox Code Playgroud)

这很简单,但在下面的情况下:

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

这也很简单,setTimeout功能asynchronousJavaScript从它和决心后跳运行它的功能,所以我们看到213.

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

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

出口132也是,为什么?这是我的问题,为什么3要跑2?我期待,因为async/await之后1的JavaScript等2,然后写了3.为什么132

Ayu*_*pta 9

await仅在传递给它的值为a时暂停Promise.在你的情况下,setTimeout返回一个Number等待不等待它.

正确的代码如下:

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