【问题标题】:how to execute promises sequentially with multiple arrays?如何使用多个数组顺序执行承诺?
【发布时间】:2018-10-03 17:05:01
【问题描述】:

我试图只在前一个成功后才调用一个承诺。我正在遍历美国的所有邮政编码并打开一个 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);
      });
    });
  });
};

【问题讨论】:

标签: javascript promise


【解决方案1】:

既然你用的是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);
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    默认情况下,es6 中的数组方法是异步的 - 你可以随时返回 oldschool 循环,因为它们将在 async/await es6 功能中同步运行

    【讨论】:

    • 需要引用。
    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多