0

I have to loop over some data and make an HTTP call to return data based on the content and after I have all the HTTP data back I need to continue and process the data.

Right now I have this.

let test;
myVar.forEach(async (x) => {
   await this.getMyDataFromService(x).subscribe(resp => {
       test.push(resp);
   }
});

//Process data
console.log(test);

when I console.log the resp is always empty and there is no data.

Thanks for the help.

Ennio
  • 1,147
  • 2
  • 17
  • 34
  • maybe define test as an array first? and console.log on test, not on resp as that is valid only inside the subscribe function. – John Caprez May 14 '20 at 21:11
  • Have a look at this to await all the async calls: https://dev.to/jamesliudotcc/how-to-use-async-await-with-map-and-promise-all-1gb5 – John Caprez May 14 '20 at 21:17
  • Your code should look like this, by using the mentioned methods. `async function yourMainFunction() { await Promise.all( myVar.map((x, i) => { this.getMyDataFromService(x).subscribe(resp => { test.push(resp); }) }) ); }` Also, the value of _resp_ is empty, because that variable is available only within the scope of subscribe's callback function. You can see the value of created _test_ array. – Armine Abramyan May 14 '20 at 21:21
  • Sorry at the end didn’t mean REsp meant test. – Ennio May 14 '20 at 21:23

0 Answers0