Javascript 如何处理承诺中的错误等待,而不违背另一个承诺?
我有异步函数:Javascript 如何处理承诺中的错误等待,而不违背另一个承诺?,javascript,typescript,Javascript,Typescript,我有异步函数: 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(c
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()
。如何运行等待新主题层
和等待新公共层
独立,现在等待新公共层
等待等待新主题层
如果一个承诺成功了,另一个承诺没有成功,该如何处理呢?使用promise.all
您可以不用wait,而是通过以下方式解决承诺:
让thematicLayers=新的thematicLayers(this.userRoles)。
thematicLayers.get().then(响应=>{
arr.push(响应);
}).catch(err=>console.log(err))
;
让customLayers=新的CommonLayers(this.userRoles)
customLayers.get().then(响应=>{
arr.push(响应);
}).catch(err=>console.log(err));
也许它们需要在单独的try/catch块中?将它们放在两个单独的try/catch
块中?是的,我想,这是一种好方法吗?以及如何独立运行它们?为什么不使用让thematicLayers=等待新的thematicLayers(this.userRoles).get().catch(e=>{})
?@daddygames,因为新thematicLayers
可能会也可能不会返回拒绝。他没有具体说明。我需要独立执行它们,在你的情况下,在另一个失败的情况下,这意味着所有承诺都失败了。
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
});