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");
})
}