簡體   English   中英

執行多個等待 promise.All 未正確捕獲錯誤

[英]executing multiple await promise.All not catching the error correctly

我試圖使用 promise all => 這只是一個代碼示例 - 每次獲得數字 72 時都會拋出多個 pormises。我在調用 executePromises 的 function 中有一個簡單的捕獲,但它沒有按應有的捕獲。 問題是即使第一個 promise 塊失敗,第二個塊也會被執行。 所以,所有的承諾都執行了,失敗發生在 2 個塊中,我得到一個未處理的異常。 如果只有 1 個塊失敗,則捕獲是正確的並且工作正常。 在調試中,即使 promise 被拒絕,它也會繼續運行這些塊 - 我認為這是因為它們以“並行”方式運行,但如果同一個塊中有 2 個錯誤,它不會拋出兩次,所以這是有道理的。

我也嘗試對 promise 使用 a.catch ,但它也沒有幫助,第二塊沒有到達那里。 還嘗試在同一個捕獲中拋出錯誤也沒有幫助。

class testClass{  
async test(num: number): Promise<{ failed_skus: { id: string }[] }> {
  return new Promise((resolve, reject) => {
  setTimeout(() => {
    if (num === 72) {
      reject(new Error(`index : ${index}, num : ${num}`));
      index++;
    } else {
      resolve({ failed_skus: [{ id: 'str' }] });
      index++;
    }
  }, 1300);
});
}

async executePromises(): Promise<void> {

index = 0;
const productUpdateRequests = [
  72,
  900,
  3,
  4,
  5,
  6,
  72,
  800,
  9,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  1,
  2,
  3,
  4,
  5,
  6,
  72,
  100,
  9,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9,
];

const productsUpdatesRequestsPromises = productUpdateRequests.map(this.test.bind(this));

const requestChunks = chunk(
  productsUpdatesRequestsPromises,
  20,
);
for (const requestChunk of requestChunks) {
  const updateStockResponses = await Promise.all(requestChunk);
}

} }

承諾的綁定和設置讓我感到困惑。 這是您的代碼的工作版本。

您可能在綁定的test() function 中需要this.index (不僅僅是“索引”)。 我沒有將它設為 class 變量,因為由於 NodeJS 計時,我不確定您能否保證訂單與數組匹配。 我的版本只使用數組索引。

此外,我發現一次映射所有測試函數會同時開始運行它們,基本上在 1.3 秒后完成程序。 在我的代碼中,我只對我所在的塊開始了測試 function,所以每個塊需要 1.3 秒。

哦,我沒有看到chunk() function,所以我做了一個。

我希望你覺得這有幫助。 快樂編碼

 function chunk(array, chunkSize) { let chunks = [] for (let i = 0; i < array.length; i += chunkSize) { chunks.push(array.slice(i, i + chunkSize)) } return chunks } class testClass { async test(num, idx) { return new Promise((resolve, reject) => { setTimeout(() => { if (num === 72) { reject(new Error(`index: ${idx}, num: ${num}`)) } else { resolve({ failed_skus: [{ id: 'str' }] }) } }, 1300) }) } async executePromises() { let processedChunks = 1 const productUpdateRequests = [ 72, 900, 3, 4, 5, 6, 72, 800, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 72, 100, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, ] const requestChunks = chunk(productUpdateRequests, 20) for (const requestChunk of requestChunks) { const updateStockResponses = await Promise.all(requestChunk.map((num, idx) => this.test(num, idx))).then(() => { console.log('Finished processing chunk ' + processedChunks) }).catch((error) => { //console.log(error) console.log('Error processing chunk ' + processedChunks) }) processedChunks++ } } } let c = new testClass() c.executePromises()

暫無
暫無

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

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