首页 > 解决方案 > 解决/拒绝后承诺无法运行代码

问题描述

我在异步函数中有异步函数。在第二个中,我必须等待承诺解决或拒绝,然后运行下面的其他代码。但是,如果承诺拒绝我的代码停止并且不运行其他功能。我该如何解决?

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")
  })
})

标签: javascriptreactjspromise

解决方案


试试这个代码,它应该查明发生错误或拒绝的位置(即它肯定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,因为在你发布的代码中它是完全没有必要的


推荐阅读