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