簡體   English   中英

如何使用多個數組順序執行Promise?

[英]how to execute promises sequentially with multiple arrays?

我只想在前一個成功之后就做出承諾。 我正在遍歷美國的所有郵政編碼,並找到一個api來從中獲取信息。 我需要的諾言是一個接一個地執行,而不是並行執行。

這是我當前的代碼。

const fetchDealersByZipProx = function() {
  const prox = [30, 50, 100];
  states.map(({ abbr }) => {
    zipcodes.lookupByState(abbr).map(({ zip }) => {
      prox.map(async p => {
        const result = await fetch(
          `${apiBaseURL}/${zip}/${p}`
        ).then(res => res.json);
        console.log(result);
      });
    });
  });
};

由於無論如何您都在使用async / await ,因此只需編寫一個普通循環即可:

async function fetchDealersByZipProx() {
  const prox = [30, 50, 100];
  for (const {abbr} of states) {
    for (const {zip} of zipcodes.lookupByState(abbr)) {
      for (const p of prox) {
        const res = await fetch(`${apiBaseURL}/${zip}/${p}`);
        const result = await res.json(); // needs a method call, btw
        console.log(result);
      }
    }
  }
}

es6中的數組方法默認情況下是異步的-您始終可以返回到老式循環,因為它們將在async / await es6功能內同步運行

暫無
暫無

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

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