0

Say I have two arrays of URLs, arr1 and arr2.

I need to fetch arr1[0] then arr1[1], arr1[2] etc. in a synchronized manner one after another (and only after the previous URL has been resolved).

Once all the items in arr1 have been fetched asynchronously, all the items in arr2 will need to be fetched asynchronously.

E.g.

// For the following arrays and URLs
const arr1 = [url1, url2, url3]
const arr2 = [url4, url5]

// The following URLs need to be fetched in this order
// only after each respective previous URL has been resolved
// url1, url2, url3, url4, url5

My code is below and I've tried many iterations of it but it seems like my console.log fires prematurely - before all the URLs have been fetched asynchronously.

What am I missing here?

function handleSubmit(arr1, arr2) {
  function getFoo(url) {
    return axios.get(url);
  }

  function getBar(url) {
    return axios.get(url);
  }

  function getFoos(arr) {
    if (arr.length > 0) {
      arr.map(async (i) => {
        await getFoo(i);
      }
    } else {
      return Promise.resolve();
    }
  }

  function getBars(arr) {
    if (arr.length > 0) {
      arr.map(async (i) => {
        await getBar(i);
      }
    } else {
      return Promise.resolve();
    }
  }

  getFoos(arr1)
    .then(() => {
      return getBars(arr2);
    })
    .then(() => {
      console.log("Foos and Bars all fetched");
    })
}

Edit:

I also tried async.mapSeries but that doesn't work either:

function handleSubmit(arr1, arr2) {
  function getFoo(url) {
    return axios.get(url);
  }

  function getBar(url) {
    return axios.get(url);
  }

  function getFoos(arr) {
    if (arr.length > 0) {
      mapSeries(arr, async (i) => {
        await getBar(i);
      }
    } else {
      return Promise.resolve();
    }
  }

  function getBars(arr) {
    if (arr.length > 0) {
      mapSeries(arr, async (i) => {
        await getBar(i);
      }
    } else {
      return Promise.resolve();
    }
  }

  getFoos(arr1)
    .then(() => {
      return getBars(arr2);
    })
    .then(() => {
      console.log("Foos and Bars all fetched");
    })
}
Chris
  • 298
  • 2
  • 14
  • use `for..loop` instead of `Array.map` – hoangdv Apr 30 '22 at 03:27
  • @hoangdv I've tried that too. That was actually my original code but I saw on stackoverflow that map() allows promises to be async and collated whereas for loop does not? – Chris Apr 30 '22 at 03:30
  • Does this answer your question? [Use async await with Array.map](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map) – hoangdv Apr 30 '22 at 03:31
  • Hm, I have no clue where I got my previous info from. I tried using a for loop again and it works now. Thanks for pointing me back in the right direction :) – Chris Apr 30 '22 at 03:33

0 Answers0