Home > Back-end >  Javascript - .catch async callback
Javascript - .catch async callback

Time:09-17

Is it an anti-pattern to use an async method for catching errors?

await something().catch(aysnc (err) => {
   console.log(err);
   await rollback();
});

I am doing this because I need to make sure that the rollback has been executed before letting the user execute the method again:

const method = async () => {
   if(isExecuting.current) return;

   isExecuting.current = true;


   await something().catch(aysnc (err) => {
       console.log(err);
       await rollback(); <--- I NEED TO AWAIT THIS TOO 
   });

   
   isExecuting.current = false;
}

CodePudding user response:

you can do it more clearly using try and catch

const method = async() => {
  if (isExecuting.current) return;
  isExecuting.current = true;

  try {
    await something();
  } catch (err) {
    console.log(err);
    await rollback();
  }
  
  isExecuting.current = false;
}

  • Related