Notification texts go here Contact Us Buy Now!

Promise: Ignore Catch and Return to Chain

<p>If you need just ignore all error in promiseA, you can just do it like that:</p>

<code>
promiseA()
  .catch(function(error){
      //just do nothing, returns promise resolved with undefined
  })
  .then(promiseB)
  .then(promiseC)
</code>

<p>If you need to run promiseB only when error.type == 'missing', you can do that:</p>

<code>
promiseA()
  .catch(function(error, ignore){
     if(error.type == 'missing'){
        return promiseB.then(promiseC)
     }
  })
</code>

<p>Here's the synchronous analogy:</p>

<code>
try {
  actionA(); // throws
  actionB(); // skipped
  actionC(); // skipped
} catch (e) {
  // can't resume
}
</code>

<p>but you want:</p>

<code>
try{
   try {
      actionA(); // throws
   } catch (e) {
      if(error.type !== 'missing'){
         throw error; // abort chain
      }
      // keep going
  }
  actionB(); // executes normally if error type was 'missing'
  actionC();
} catch (e) {
  // handle errors which are not of type 'missing'.
}
</code>

<p>Here's the promise version:</p>

<code>
asyncActionA()        // <-- fails with 'missing' reason
   .catch(error => {
      if(error.type !== 'missing'){
         throw error; // abort chain. throw is implicit Promise.reject(error); 
      }
      // keep going, implicit: return Promise.resolve();
   })
   .asyncActionB(promiseB) // <-- runs
   .asyncActionC(promiseC)
   .catch(err => {
      // handle errors which are not of type 'missing'.
   });
</code>

<p>The easiest and safest way to ignore promise errors is void that error. This approach is ESLint friendly too.</p>

<code>
const myPromise1 =async()=>{
  throw new Error('explicitly rejected')
}
const myPromise2 =async()=>{
  console.log('passed');
}

myPromise1()
  .then(myPromise2())
  .catch(e=>void e)
</code>

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.