Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise: Ignore Catch and Return to Chain

Is it possible to ignore a catch and return back to the chain?

promiseA()        // <-- fails with 'missing' reason
  .then(promiseB) // <-- these are not going to run 
  .then(promiseC)
  .catch(function(error, ignore){
     if(error.type == 'missing'){
        ignore()  // <-- ignore the catch and run promiseB and promiseC
     }
  })

Is something like this possible?

like image 426
Adam Halasz Avatar asked Apr 13 '16 11:04

Adam Halasz


People also ask

Does promise catch return a promise?

This function has one argument: reason. The rejection reason. The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is fulfilled.

Does promise reject to catch?

The code of a promise executor and promise handlers has an "invisible try.. catch " around it. If an exception happens, it gets caught and treated as a rejection.

Can I return a promise with a then?

then() The then() method returns a Promise . It takes up to two arguments: callback functions for the success and failure cases of the Promise .

What is the difference between promise all and promise allSettled?

all() method returns an array as an output containing promise data inside several indexes. Promise. allSettled() method returns an array of objects and each of these objects further contains two properties further status and value.


2 Answers

Here's the synchronous analogy:

try {
  action1(); // throws
  action2(); // skipped
  action3(); // skipped
} catch (e) {
  // can't resume
}

vs

try {
  action1(); // throws
} catch (e) {
  handleError(e);
}
action2(); // executes normally
action3();

Here's the promise version:

asyncActionA()        // <-- fails with 'missing' reason
.catch(error => {
   if(error.type == 'missing'){
      return; // Makes sure the promise is resolved, so the chain continues
   }
   throw error; // Otherwise, rethrow to keep the Promise rejected
})
.asyncActionB(promiseB) // <-- runs
.asyncActionC(promiseC)
.catch(err => {
  // Handle errors which are not of type 'missing'.
});
like image 136
Madara's Ghost Avatar answered Oct 09 '22 02:10

Madara's Ghost


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

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

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

promiseA()       
  .catch(function(error, ignore){
     if(error.type == 'missing'){
        return promiseB.then(promiseC)  
     }
  })
like image 37
Nikolai Mavrenkov Avatar answered Oct 09 '22 01:10

Nikolai Mavrenkov