i在异步函数中具有异步函数。在第二次,我必须等待承诺解决或拒绝,然后在下面运行其他代码之后。但是,如果承诺拒绝我的代码停止而没有运行其他功能。我如何修复它?
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")
})
})
承诺无法正确链接,axios.patch(...)
承诺不会返回。await
是then
和catch
的句法糖,其目的是在可能的情况下摆脱嵌套功能。应该是:
const res = await axios.all(promises)
await axios.patch("/url", { foo: bar })
const promises2 = arr.map(item => {
return axios.post("/url-2", item)
});
try {
await Promise.all(promises2)
console.log("resolved"))
} catch (err) {
console.log("failed");
}
您的代码顺序是错误的。当然,如果第一个承诺被拒绝,那么其余的将不会被调用。
尝试以这种方式重写您的代码:
let res = await axios.all(promises).catch(() => { console.log("failed"); return false; });
if (!res) {
// Do something when rejected
....
}
// Call the 2nd promise
let res2 = await axios.path("/url", {foo: bar}).catch(() => {console.log("failed 2"); return false; });
if (!res2) {
// Do something when the 2nd promise is rejected
...
}
// Call your last promise
let res3 = await Promise.all(promises2).catch(() => {console.log("failed 3"); return false; });
if (!res3) {
// Do something if it is rejected again
....
}
// Otherwise, do your thing
尝试以下代码,它应该指出发生错误或拒绝的地方(即绝对是在运行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));
注意,我已删除了异步/等待,因为在您发布的代码中,它完全不必要