Home > Mobile >  How can I skip chained promises resulting in exceptions?
How can I skip chained promises resulting in exceptions?

Time:12-07

I have multiple apis to hit.

E.g

callApis = async function () {

  try {

    var apis = ["apiWithSucess1", "apiWithException", "apiWithSucess1"];

    var response = "";

    for(var i = 0; i < apis.length; i  ){

      const apiResponse = await httpRequest.get(apis[i]).promise(); 

      response =apiResponse.data;
    }

    return response;
  } 
  catch (err) {
    console.log("Exception => ", err);
  }
};

callApis().then(function(result){

  console.dir(result);
  
}).catch(function(err) {
  
  console.log(err); 
});

Now when I call this and if there is some api in array that throws exception, it crashes all the process. I want the api with exception to be skipped.

CodePudding user response:

Insert a try/catch clause:

...
let apiResponse
for(var i = 0; i < apis.length; i  ){
  try {
    apiResponse = await httpRequest.get(apis[i]).promise(); 
  catch (error) {
     continue
  }
  response =apiResponse.data;
}
...

Anything in a try clause will run normally, unless an exception/error is thrown. In that case, it ends up in the catch clause, where one can handle the issue. I've simply placed a continue statement there so you only get good responses, though you can also add a null into the response, and then continue, so that your response array is ordered.

CodePudding user response:

You can catch errors with try/catch as in Michal Burgunder's answer, but if it is not important that the APIs are chained or otherwise called in sequence, then you have the opportunity to call them in parallel to make the process faster. This would entail calling Promise.allSettled() (or Promise.all(), if you mute errors with .promise().catch(() => "")).

callApis = /* no longer async */ function () {
  var apis = ["apiWithSucess1", "apiWithException", "apiWithSucess1"];
  // For each API, call promise() and mute errors with catch().
  // Call Promise.all to wait for all results in parallel.
  return Promise.all(apis.map(x => httpRequest.get(x).promise().catch(() => "")))
      // Join the results array as a string with no separators.
      .then(arrayOfStrings => arrayOfStrings.join(''))
      // If any of the above steps fails, log to console and return undefined.
      .catch(err => { console.log("Exception => ", err); });
}
  • Related