簡體   English   中英

解決/拒絕后,承諾無法運行代碼

[英]Promises can't run code after resolve/reject

我在異步功能中有一個異步功能。 在第二個步驟中,我必須等待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")
  })
})

承諾未正確鏈接, 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));

注意,我已經刪除了async / await,因為在您發布的代碼中完全沒有必要

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM