我在异步功能中具有异步功能。在第二个步骤中,我必须等待promise解决或拒绝时以及在运行下面的其他代码之后。但是如果诺言拒绝我的代码停止并且不运行其他功能。我该如何解决?
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")
})
})
答案 0 :(得分:0)
承诺未正确链接,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");
}
答案 1 :(得分:0)
您的代码顺序错误。当然,如果第一个承诺被拒绝,那么其余的将不会被调用。
尝试以这种方式重写代码:
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
答案 2 :(得分:0)
尝试这段代码,它应该指出错误或拒绝发生的位置(即肯定是在运行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,因为在您发布的代码中完全没有必要