javascript - 解决/拒绝后承诺无法运行代码
问题描述
我在异步函数中有异步函数。在第二个中,我必须等待承诺解决或拒绝,然后运行下面的其他代码。但是,如果承诺拒绝我的代码停止并且不运行其他功能。我该如何解决?
await axios.all(promises).then(res => {
axios.patch("/url", { foo: bar }).then(async () => {
const promises2 = arr.map(item => {
return axios.post("/url-2", item)
});
await Promise.all(promises2)
.then(() => console.log("resolved")) //this not calling ever
.catch(() => console.log("failed")) //this not calling ever
console.log("This console log ever not working")
})
})
解决方案
试试这个代码,它应该查明发生错误或拒绝的位置(即它肯定Promise.all(promises2)
是在运行之前
await axios.all(promises)
.then(res => axios.patch("/url", { foo: bar }), err => {
throw `all(promises) failed with ${err}`;
})
.then(() => {
const promises2 = arr.map(item => {
return axios.post("/url-2", item);
});
return Promise.all(promises2)
.then(() => console.log("resolved")) //this not calling ever
.catch(err => {
throw `all(promises2) failed with ${err}`;
});
}, err => {
throw `patch failed with ${err}`;
})
.catch(err => console.error(err));
注意我已经删除了 async/await,因为在你发布的代码中它是完全没有必要的
推荐阅读
- oracle - Oracle DB 仅在数据存在时创建表
- octobercms - 在 forceDelete() 上删除模型的文件附件 - OctoberCMS
- python - 如何使用matplotlib在x轴上绘制包含日期时间对象列表的字典值的时间线图?
- sql-server - 为 SQL 中的所有可空列设置 NULL
- mysql - MySql Sum 如果条件满足 Group By
- javascript - 如何在 Angular 中的 httpClient 调用中产生错误?
- javascript - 使用 JavaScript 检查元素是否具有特定的 CSS 属性
- java - 在junit中一起使用2个RunWith()
- php - PHP Slim,返回响应时出现问题
- rust - 使用 musl 库动态链接 rust 二进制文件