簡體   English   中英

將異步函數傳遞給 promise.all()

[英]passing async functions to promise.all()

我知道promise.all()期望一系列承諾。

但是,是否可以執行以下操作? 如果不是,請提出解決方法。

不建議在for循環中使用await 這就是為什么我要推入一個數組並在上面做promise.all()的原因。

var functionArray = [];
for (let i = 0; i < jobs.length; i += 1) {
  ...
  if (params.origins !== '' && params.destinations !== '') {
    functionArray.push(async function() {
      response = await getDistance(params.origins, params.destinations);
      if (response.error) {
        // handle error
        return null
      } else {
        distances = response.data.rows[0].elements.map((el, index) => {
          el.emp_id = empIdOrder[index];
          return el;
        });
        sortedDistances = sortDistance(distances);
        return formatDataForInsert(jobs[i].job_id, sortedDistances);
      }
    });
  }
}
var dataToBeinserted = await Promise.all(functionArray); // return an array with results

它沒有按預期工作。

await Promise.all(functionArray); 總是返回[ [AsyncFunction], [AsyncFunction] ]

不是應該解決嗎?

第一個問題是Promise.all接受一組promises ,而不是一組函數 - 您當前的代碼將不起作用。

主要問題是您只是有條件地使用異步操作的結果。 您可以將.then鏈接到 Promise 以使 Promise 解析為.then的結果,而不是其初始解析值。 那是:

Promise.resolve(2)
  .then(res => res + 4)

導致解析為 6 的 Promise。

使用此邏輯,您可以將 Promise 推送到數組,該數組在其then中有條件地處理結果( distances = response.data... )並返回最終值,或者不返回任何內容。 最后,在 Promise 數組上調用Promise.all ,並按 boolean 過濾:

const promises = [];
for (let i = 0; i < jobs.length; i += 1) {
  if (params.origins !== '' && params.destinations !== '') {
    promises.push(
      getDistance(params.origins, params.destinations)
        .then((response) => {
          if (response.error) {
            // handle error
            return null
          } else {
            const distances = response.data.rows[0].elements.map((el, index) => {
              el.emp_id = empIdOrder[index];
              return el;
            });
            const sortedDistances = sortDistance(distances);
            return formatDataForInsert(jobs[i].job_id, sortedDistances);
          }
      })
    );
    }
}
const results = await Promise.all(promises)
  .filter(Boolean); // filter out failures

var dataToBeinserted = await Promise.all(functionArray); // return an array with results

您的示例中的 function 永遠不會執行,為了讓他們解決您可以這樣做(將其放在括號中並立即調用):

functionArray.push((async function() {
  response = await getDistance(params.origins, params.destinations);
  if (response.error) {
    // handle error
    return null
  } else {
    distances = response.data.rows[0].elements.map((el, index) => {
      el.emp_id = empIdOrder[index];
      return el;
    });
    sortedDistances = sortDistance(distances);
    return formatDataForInsert(jobs[i].job_id, sortedDistances);
  }
})());

或者:

Promise.all(fnArray.map(f => f())

您應該將 Promise object 推送到陣列。 所以只需用 Promise 包裝異步 function。

暫無
暫無

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

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