Home > Mobile >  Catch promise rejection in nested function
Catch promise rejection in nested function

Time:09-25

I have this repro: https://codesandbox.io/s/jolly-bogdan-k6ii4?file=/src/index.ts

code:

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();

When this is ran in Node.js, the reject will throw after 3s, and blow up the whole process with an "unhandledRejection Error" - where can one catch this error to avoid an unhandledRejection Error, but allow it to propagate up to the catch inside the main function?

CodePudding user response:

You need to await it.

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

CodePudding user response:

The problem is that you're not waiting for the promise to resolve before moving forward and the error is thrown then outside of the try block.

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");
  // }
};
  • Related