簡體   English   中英

Promise allSettled running before promise finally

[英]Promise allSettled running before promise finally

我有一個 function 嘗試加載 web 圖像並跟蹤加載圖像的計數和失敗圖像的計數。 我正在使用fetch加載圖像,並在驗證所有圖像后使用Promise.allSettled運行操作。

const data = ["/test1.png", "/test2.png", "/test3.png"];
let imagesValidated = 0;
let imagesFailed = 0;
const promiseArr = [];

data.forEach((item) => {
  const imgPromise = fetch(item);
  promiseArr.push(imgPromise);

  imgPromise
    .then((resp) => {
      if (!resp.ok()) imagesFailed += 1;
    })
    .catch((error) => {
      imagesFailed += 1;
    })
    .finally(() => {
      // For the last image `test3.png`, the finally blocks runs after `allSettled`.
      imagesValidated += 1;
    });
});

Promise.allSettled(promiseArr).then(() => {
  // some operations
});

我面臨的問題是 finally 塊。 對於最后一張圖片,finally 塊在allSettled回調之后運行。 這會導致imagesValidated小於實際掃描的圖像數。 我不想刪除 finally 塊,因為將來我會在其中添加更多清理代碼。

這是 Promise 解析方法的預期行為嗎? 有沒有一種方法可以在不刪除 finally 塊的情況下修復此代碼?

您正在將fetch Promise 推送到數組 - 而不是通過.then.finally的鏈。 將整個鏈式 Promise 推入數組。

data.forEach((item) => {
  promiseArr.push(
  fetch(item)
    .then((resp) => {
      if (!resp.ok()) imagesFailed += 1;
    })
    .catch((error) => {
      imagesFailed += 1;
    })
    .finally(() => {
      // For the last image `test3.png`, the finally blocks runs after `allSettled`.
      imagesValidated += 1;
    })
  );
});

Promise.allSettled(promiseArr).then(() => {
  // some operations
});

或者,更好的是,對原始數據使用.map

Promise.allSettled(
  data.map(item => fetch(item)
    .then((resp) => {
      if (!resp.ok()) imagesFailed += 1;
    })
    .catch((error) => {
      imagesFailed += 1;
    })
    .finally(() => {
      // For the last image `test3.png`, the finally blocks runs after `allSettled`.
      imagesValidated += 1;
    })
)
  .then(() => {
    // some operations
  });

不過,請注意,使用Promise.allSettled在這里對您沒有多大幫助 - 由於.catch ,Promises 都不能拒絕。 考慮使用Promise.all ,或僅使用Promise.allSettled .fetch ,這樣您就可以在所有響應都返回后遞增計數器。

暫無
暫無

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

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