[英]How handle error in promise await and not break another promise?
我有異步 function:
async getLayers() {
let arr = [];
try {
let thematicLayers = await new ThematicLayers(this.userRoles).get();
let customLayers = await new CommonLayers(this.userRoles).get();
arr.push(thematicLayers);
arr.push(customLayers);
} catch(err) {
console.log('_________________');
console.log(err);
}
}
如果至少有一個 promise 返回異常,它會出現catch()
。 如何運行await new ThematicLayers
和await new CommonLayers
獨立,現在await new CommonLayer
await await new ThematicLayers
。
如果一個 promise 成功,另一個不成功,如何處理案例?
使用 Promise.all https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Promise.all([
new ThematicLayers(this.userRoles).get(),
new CommonLayers(this.userRoles).get()
]).then(value =>
{
console.log(value);
// your code
}, reason =>
{
console.log(reason)
// your code
});
您可以不使用 await,而是使用.then 解決承諾,如下所示:
let thematicLayers = new ThematicLayers(this.userRoles). thematicLayers.get().then(response => { arr.push(response); }).catch(err => console.log(err)); let customLayers = new CommonLayers(this.userRoles) customLayers.get().then(response => { arr.push(response); }).catch(err => console.log(err));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.