【问题标题】:Typescript - unexpected sequence with setTimeout in combination with async and awaitTypescript - setTimeout 与 async 和 await 结合的意外序列
【发布时间】:2021-12-08 11:52:39
【问题描述】:

当我运行这个脚本时,输出与我预期的不同:1 到 4。这是为什么?

const delay2 = async ( ms: number) => setTimeout( () => {
  console.log( '2 - timeout')
}, ms);

const mainAsync2 = async () => {
  console.log( '1 - before');
  await delay2( 2000);
  console.log( '3 - after');
}
mainAsync2()
.then( res => console.log( '4 - done'));

输出是:

1 - before
3 - after
4 - done
2 - timeout

【问题讨论】:

    标签: typescript async-await


    【解决方案1】:

    setTimeout 本身不返回承诺,所以awaiting 它什么也不做。它只是为ms 毫秒设置超时。相反,您应该让您的 delay2 返回一个在 ms 毫秒后解析的承诺,例如:

    const delay2 = async (ms: number) =>
        new Promise(res => setTimeout(() => { 
            console.log('2 - timeout');
            res();
        }, ms));
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2016-01-22
      • 2016-08-22
      • 1970-01-01
      • 2021-08-25
      • 2015-12-25
      • 2020-03-30
      相关资源
      最近更新 更多