Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
¿Cómo puedo omitir las promesas encadenadas que resultan en excepciones?

Tengo múltiples apis para golpear.

P.ej

 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); });

Ahora, cuando llamo a esto y si hay alguna API en la matriz que genera una excepción, se bloquea todo el proceso. Quiero que se omita la API con excepción.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Inserte una cláusula de try / catch :

 ... 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; } ...

Cualquier cosa en una cláusula de try se ejecutará normalmente, a menos que se produzca una excepción/error. En ese caso, termina en la cláusula de catch , donde uno puede manejar el problema. Simplemente coloqué una declaración de continue allí para que solo obtenga buenas respuestas, aunque también puede agregar un null en la respuesta y luego continue , para que su matriz de respuesta esté ordenada.

about 4 years ago · Juan Pablo Isaza Report

0

Puede detectar errores con try / catch como en la respuesta de Michal Burgunder , pero si no es importante que las API estén encadenadas o llamadas en secuencia, entonces tiene la oportunidad de llamarlas en paralelo para acelerar el proceso. Esto implicaría llamar a Promise.allSettled() (o Promise.all() , si silencia los errores con .promise().catch(() => "") ).

En sintaxis convencional:

 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); }); }

En su sintaxis async / await , además de la llamada de catch de silenciamiento de excepción en el 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!