【问题标题】:JS - Why code does not run after async / await for promiseJS - 为什么代码在异步/等待承诺后不运行
【发布时间】:2023-01-23 19:31:15
【问题描述】:

我在 TS playground 上有一个示例代码代表了我的问题。 在异步函数中,我在等待承诺后记录结果,但只记录承诺运行中的代码,而不是它之外的日志。有人可以解释这个问题吗?

这是代码:

const asyncFnc = async () => {
    let result = false;
    await new Promise(resolve => {
        setTimeout(() => {
            // This log worked
            console.log('waited 5s');
            result = true;
        }, 5000);
    });
    // This log did not worked
    console.log(result);
}

asyncFnc();

结果:

【问题讨论】:

    标签: javascript async-await promise


    【解决方案1】:

    您需要在超时时致电resolve()

    【讨论】:

      【解决方案2】:

      await 将父函数发送到睡眠状态,直到右侧的承诺解决(即解决或拒绝)。

      你的承诺绝不解决或拒绝。 (即你不调用resolve,使用第二个参数,或抛出异常)。

      因此父函数永远休眠。


      写这个的惯用方法是避免在更广泛的范围内设置变量作为副作用,而只是用值来解决。

      const asyncFnc = async () => {
          const result = await new Promise(resolve => {
              setTimeout(() => {
                  console.log('waited 5s');
                  resolve(true);
              }, 5000);
          });
          console.log(result);
      }
      
      asyncFnc();

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 2019-04-29
        • 2017-06-15
        • 1970-01-01
        • 2021-06-28
        • 2018-02-03
        • 2018-03-05
        • 1970-01-01
        相关资源
        最近更新 更多