0

Okay, so I have this function that is a simple Axios request. We know that Axios will run as a promise based request so we do something like this and push all the responses into an array

let array = []
function A() {
  return axios.get(url).then(r => r.data).then(r => array.push(r.forms))
}

The issue is now I need to call this function specifically 898 times.

async function main() {
  await someArrayWithALotOfObjects.forEach(async (e) => {
    return await A(e.url);
  });
  console.log(array);
}

The issue is when I run main() it console logs [], however when I change the main function to be completely hardcoded it outputs all the data correctly pushed to the array in a workable format.

async function main() {
  await A(someArrayWithALotOfObjects[0].url);
  await A(someArrayWithALotOfObjects[1].url);
  await A(someArrayWithALotOfObjects[2].url);
  await A(someArrayWithALotOfObjects[3].url);
  await A(someArrayWithALotOfObjects[4].url);
  await A(someArrayWithALotOfObjects[5].url);
  await A(someArrayWithALotOfObjects[6].url);
  await A(someArrayWithALotOfObjects[7].url);
  ...

  
  console.log(array);
}

So my question is how to not hardcode because the loop does not seem to be completed before I run the console.log function.

Note: eventually I will be changing the console logging to the fs event for writing to a file if this helps in writing a better solution.

Note2: IDK how to use the new yield stuff in JavaScript yet, so if that is the solution needed forgive me.

adarian
  • 334
  • 7
  • 24
  • none of the suggested problems that were similarly solved my issue... – adarian Aug 22 '21 at 01:47
  • A example for Promise in Series ```const urls = ["url0", "url1", "url2"]; async function run() { const result = []; for (const url of urls) { const response = await axios.get(url); result.push(response.data); } return result; } run().then(console.log).catch(console.log);``` – ikhvjs Aug 23 '21 at 15:01
  • The suggested questions really solve your question. You may have difficulties understanding it then. – ikhvjs Aug 23 '21 at 15:03
  • I was able to use the 'for of' option, but I had to add quiet a bit of other code handlers to get it to work. – adarian Sep 09 '21 at 23:01

0 Answers0