0
  • Part I

so I have the following code =>

let array = [];

await objElements.forEach( async(element) => {
  let results = await axios.get('backend_route', {params: element});
  results.data.forEach(result => {
    array.push(result);

    console.log(result);
    console.log(array);
//  here the `result` variable is printed with the desired value and the array shows all the `result` singles values on it
  });
});

console.log(array);
// But here, like if I would like to return the array at the end, it is empty :(

This is on JavaScript ES6 btw, if you have any possible solution any help is appreciated, thanks!

  • Part II

Thanks for answering the previous question, I have been reading from Promises and still cannot figure out the new problem I have, so the code goes as following =>

const promise = array.map(async(item) => {
  // here for each `item` I'm doing a call to the backend.
  let response = await axios.get('route_to_backend', {params: item});
  console.log(response);

  /*When I try to get the response from the backend, it always send me
  the response for the last `item` of the array, example: if the
  array is [12, 67, 95, 06], it will make the request to the backend 4
  times (length of the array) and always with the last item of the
  array (in this example `06`) :(*/
});

//Finally as per the example I was provided
await Promise.all(promise);

Thanks a lot for your answers (Y)

  • can you post a executable snippet instead [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Akash Shrivastava Dec 31 '19 at 13:13
  • You're console.logging `array` syncronously but not waiting for the results that you get from your async function – TKoL Dec 31 '19 at 13:14
  • you need to use a promise – BugsForBreakfast Dec 31 '19 at 13:16
  • async function f() { let array = []; for(let i=0; i { array.push(result); console.log(result); console.log(array); // here the `result` variable is printed with the desired value and the array shows all the `result` singles values on it }); } console.log(array); } You can use like this. – Jeba Dec 31 '19 at 13:20
  • You can also use `forof` loop for this.`let array = []; for(let element of objElements){ let results = await axios.get('backend_route', {params: element}); for(let result of results.data) { array.push(result); console.log(result); console.log(array); } } console.log(array);` – Zunnurain Badar Dec 31 '19 at 13:23

1 Answers1

0

await objElements.forEach( async(element) => { won't actually await the inner async function.

What you really want to do is something more like:

const promises = objElements.map(async (element) => {...});
const results = await Promise.all(promises);

This creates a list of promises with .map and then awaits the Promise.all joining of them.

results should be an array with whatever the promises resolved with, ie whatever your internal async function returns

TKoL
  • 13,158
  • 3
  • 39
  • 73