使用 setTimeout 连续异步/等待

Hid*_*ide 1 javascript async-await ecmascript-6

我是 ES6 的新手,所以我研究了 Javascript 的声明。

在测试 async/await 时,我发现了一些奇怪的行为。

我写了这样的代码,

const test = async () => {
    await setTimeout(() => {
        console.log("timeout");
    }, 2000);
    await console.log(1);
    await console.log(2);
}

test();
Run Code Online (Sandbox Code Playgroud)

输出在这里,

1
2
timeout
[Finished in 2.1s]
Run Code Online (Sandbox Code Playgroud)

我将 async 定义为功能并等待每一行同步工作。

预期输出在这里,

timeout
1
2
[Finished in 2.1s]
Run Code Online (Sandbox Code Playgroud)

为什么这段代码不能同步?

谢谢。

Joh*_*anP 6

这就是您如何获得所需的输出。您可以将您的包裹setTimeout在 aPromiseawaitit 中。

const test = async () => {
    await new Promise((resolve)=>setTimeout(() => {
        console.log("timeout");
        resolve();
    }, 2000)); 
    console.log(1);
    console.log(2);
}

test();
Run Code Online (Sandbox Code Playgroud)

  • 虽然真的没有任何理由将 `console.log` 包装在承诺中...... *“你只能在承诺上`await`”* 那不是真的。你可以`await`任何值。但如果它不是承诺,它只会立即返回值。 (2认同)
  • 但是你也不能`await console.log`。所以可能删除两个无用的`await`太lol (2认同)