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