我有多個 api 需要點擊。
例如
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);
});
現在,當我呼叫它時,如果陣列中有一些 api 拋出例外,它會導致所有行程崩潰。我希望跳過 api 例外。
uj5u.com熱心網友回復:
插入一個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;
}
...
try除非拋出例外/錯誤,否則子句中的任何內容都將正常運行。在那種情況下,它最終出現在catch子句中,在那里人們可以處理問題。我只是在continue那里放置了一條陳述句,因此您只會得到好的回應,不過您也可以null在回應中添加 a ,然后continue,以便對您的回應陣列進行排序。
uj5u.com熱心網友回復:
您可以使用try/捕獲錯誤,catch如Michal Burgunder 的回答中所述,但如果 API 被鏈接或以其他方式按順序呼叫并不重要,那么您就有機會并行呼叫它們以使程序更快。這將需要呼叫Promise.allSettled()(或者Promise.all(),如果您使用 使錯誤靜音.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); });
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375629.html
標籤:javascript 打字稿 异步等待 承诺
上一篇:需要幫助來轉換打字稿助手
