0

I'm making a backend server with Node.js (based on Nest.js). Each route handler mainly queries/modifies the database (main effect), and sometimes send events to external server, leave log and etc (side effect).

I want each route handler functions not to fail when only side effect throws error and main effect goes well(behavior 1). And I also want the side effects to be executed in parallel with the main effect so that the time executing each route handler functions can be decreased(behavior 2).

How can I achieve this behavior in javascript? I first tried this code:

async routeHandler() {
  sideEffect().catch(console.error)

  await mainEffect();
}

However, when the sideEffect function throws an error, the routeHandler function fails. I can try next, but it does not satisfies the behavior 2.

async routeHandler() {
  try {
    await sideEffect();
  } catch (error) {
    console.error(error);
  }

  await mainEffect();
}
김승수
  • 171
  • 2
  • 9
  • "*when the `sideEffect` function throws an error*" - do you mean it returns a promise that will reject? It appears to be an asynchronous function, so it [must *never* synchronously throw](https://stackoverflow.com/q/21887856/1048572). – Bergi Dec 21 '21 at 08:57
  • `sideEffect().catch(console.error);` is [just what you want](https://stackoverflow.com/q/32384449/1048572). – Bergi Dec 21 '21 at 09:01
  • @Bergi Yes. The `sideEffect` function is asynchronous. However, if the `sideEffect` function rejects before the `routeHandler` function resolves, the execution of `mainEffect` function stops. – 김승수 Dec 21 '21 at 13:15
  • No, it doesn't. Unless the effects are somehow related, the `mainEffect` will not be affected. If you still does with your code, please provide a [mcve]. – Bergi Dec 21 '21 at 17:14

1 Answers1

-1

maybe what you are looking to use is Promise.allSettled?

  • Run async tasks in parallel
  • the other async tasks should still continue even if the other tasks has been rejected

Link for the docs: check the compatibility section as well.

lemongrab
  • 9
  • 3