【问题标题】:Catch promise rejection in nested function在嵌套函数中捕获承诺拒绝
【发布时间】:2021-09-24 23:13:22
【问题描述】:

我有这个复制品:https://codesandbox.io/s/jolly-bogdan-k6ii4?file=/src/index.ts

代码:

const wait = (timeoutMs: number) => {
  let timeoutHandle: number | undefined;

  const promise = new Promise((_resolve, reject) => {
    timeoutHandle = setTimeout(() => {
      reject(`wait timed out after ${timeoutMs} ms`);
    }, timeoutMs);
  });

  return {
    promise,
    cancel: (): void => clearTimeout(timeoutHandle)
  };
};

const waitBy = (timeoutMs: number) => {
  const res = wait(timeoutMs);
  return res;
};

const main = async () => {
  try {
    const { promise, cancel } = waitBy(3000);
  } catch (error) {
    console.log("failed on timeout");
  }
  // try {
  //   await promise;
  // } catch (error) {
  //   console.log("timed out");
  // }
};

main();

当它在 Node.js 中运行时,reject 将在 3 秒后抛出,并以“unhandledRejection 错误”炸毁整个过程 - catch 这个错误在哪里可以避免 unhandledRejection 错误,但允许它传播到main 函数内的catch

【问题讨论】:

    标签: node.js promise


    【解决方案1】:

    问题是你没有等待承诺解决,然后继续前进,然后错误被抛出 try 块之外。

    const main = async () => {
      try {
        const { promise, cancel } = waitBy(3000);
        await promise // new code
      } catch (error) {
        console.log("failed on timeout");
      }
      // try {
      //   await promise;
      // } catch (error) {
      //   console.log("timed out");
      // }
    };
    

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多