0

I am trying to only call a promise once the previous one has succeeded. I am looping through all the zipcodes in the us and hitting up an api to get information back from it. I need the promises to execute after one another and not in parallel.

here is my current code.

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);
      });
    });
  });
};
Taylor Austin
  • 5,407
  • 15
  • 58
  • 103
  • 1
    Possible duplicate of [Chaining promises in a waterfall](https://stackoverflow.com/questions/40579896/chaining-promises-in-a-waterfall) – zero298 Apr 23 '18 at 15:28

2 Answers2

3

Since you're using async/await anyway, just write a normal loop:

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);
      }
    }
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-3

Array methods in es6 are async by default - you can always go back to oldschool loops as they will run synchronously within async/await es6 functionality

James Bass Davies
  • 408
  • 1
  • 3
  • 11