Promises can't run code after resolve/reject

问题: I have async function in async function. In the second I must wait when promises resolve or reject and after run other code below. But if promise reject my code stopping an...

问题:

I have async function in async function. In the second I must wait when promises resolve or reject and after run other code below. But if promise reject my code stopping and no run other functions. How I can fix it?

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

回答1:

Promises aren't chained properly, axios.patch(...) promise isn't returned. await is syntactic sugar for then and catch, its purpose is to get rid of nested functions where possible. It should be:

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

回答2:

The order of your code is wrong. Of course if the first promise is rejected, then the rest will not be called.

Try rewriting your code this way:

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

回答3:

Try this code, it should pinpoint where the error or rejection is occurring (i.e. it's definitely before Promise.all(promises2) is run

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));

Note I've removed async/await, because in the code you've posted it is totally unnecessary

  • 发表于 2019-03-16 21:22
  • 阅读 ( 202 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除