【问题标题】:Continuous async/await with setTimeout [duplicate]使用 setTimeout 连续异步/等待 [重复]
【发布时间】:2018-12-18 22:09:53
【问题描述】:

我是 ES6 的新手,所以我研究 Javascript 的语句。

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

我是这样写代码的,

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

test();

输出在这里,

1
2
timeout
[Finished in 2.1s]

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

预期的输出在这里,

timeout
1
2
[Finished in 2.1s]

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

谢谢。

【问题讨论】:

  • 你不能await setTimeout(有意义地)因为setTimeout不返回Promise
  • async/await 是处理 promises 的语法糖。如果函数没有返回承诺,那么await 并没有真正的帮助。 await setTimeout()setTimeout() 具有相同的效果。 Read the MDN documentation about await.
  • 你也不能等待 console.log。
  • @CertainPerformance 谢谢。那么如何修复该代码以使其正常工作?
  • 创建一个返回 Promise 的函数。 (或者只是awaitPromise

标签: javascript ecmascript-6 async-await


【解决方案1】:

这是实现所需输出的方法。您可以将 setTimeout 包装在 Promiseawait 中。

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

test();

【讨论】:

  • 完美运行。谢谢:)
  • 实际上没有任何理由将console.log 包装在一个承诺中...... “你只能在承诺上await 这不是真的。您可以await 任何值。但如果它不是一个承诺,它只会立即返回值。
  • 是的,你是对的,我会更新我的答案
  • @FelixKling 感谢您的明确回答。
  • 但是你也不能await console.log。所以可能删除这两个没用的await太lol
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 2020-05-12
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
相关资源
最近更新 更多