0

If I remove the second try/catch block, would an exception occurring in the IIFE bubble-up to the first try/catch block, considering the IIFE is preceded by return?

I am trying to eliminate unnecessary try/catch blocks and understand bubbling.

const run = (
  identifier: string
): Promise<{
  installationId: string;
}> =>
  new Promise(async (resolve, reject) => {
    try {
      const { installationId } = await getInstallation(identifier);

      await updateInstallation(installationId);

      resolve({
        installationId,
      });
    } catch (errorCode) {
      if (errorCode === "installationNotFound")
        return (async () => {
          try {
            const installationId = await insertInstallation(identifier);

            resolve({
              installationId,
            });
          } catch (errorCode) {
            reject(errorCode);
          }
        })();

      reject(errorCode);
    }
  });
  • You don't need to use the promise constructor because `getInstallation` and `insertInstallation` methods already return a promise. Also the executor function (function passed to the promise constructor) shouldn't be an `async` function. See: [async executor function](https://stackoverflow.com/questions/43083696/cant-throw-error-from-within-an-async-promise-executor-function) – Yousaf Sep 27 '22 at 06:13
  • I believe I have to use async in ```new Promise(async (resolve, reject)``` because I am, indeed, using async/await within the underlying scope. Also, removing async stops await getInstallation working and doing the same within the IIFE also stops the await insertInstallation working – Craig Malton Sep 27 '22 at 10:29
  • 1
    Here's how your code could be re-written: https://pastebin.com/9djnmTbF – Yousaf Sep 27 '22 at 11:06
  • You are employing a [promise construction anti-pattern](https://stackoverflow.com/q/23803743/5459839) – trincot Sep 27 '22 at 14:06
  • Thanks Yousaf! I think I understand the refactored code! – Craig Malton Oct 03 '22 at 12:39

0 Answers0