Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
How can I skip chained promises resulting in exceptions?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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) {
     console.error(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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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(() => "")).

In conventional syntax:

callApis = /* no longer async */ function () {
  var apis = ["apiWithSuccess1", "apiWithException", "apiWithSuccess1"];
  // 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); });
}

In your async/await syntax, aside from the exception-muting catch call in the map:

callApis = async function () {
  try {
    var apis = ["apiWithSuccess1", "apiWithException", "apiWithSuccess1"];
    // For each API, call promise() and mute errors with catch().
    // Call Promise.all to wait for all results in parallel.
    var responseArray = await Promise.all(apis.map(
        x => httpRequest.get(x).promise().catch(() => "")));
    // Join the results array as a string with no separators.
    return responseArray.join(""));
  } 
  catch (err) {
    console.log("Exception => ", err);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda