I have a question regarding this code.
let results = [1, 2 ,3 4]
randomArray.forEach( async (e, i) => {
externalApi(e).subscribe(async ({data}) => {
results.push(data);
console.log("result", e);
}, (error) => {
console.log(error)
});
});
As you can see I am iterating over an array to get multiple results from an api and store them in results
, in theory it works but because the call to the api is a promise, the results.push(data)
, is not going to be executed immediately, so I would expect 2 things.
- That results had no values at the end of the iteration
- After some time results will store the values obtained from the api
This in theory happens but I get these results:
// console results
$"result, 1"
$"result, 2"
$"result, 2"
$"result, 1"
$"result, 3"
$"result, 4"
This leaves me confused because, although asyncrona
the job is running correctly, it seems that the iteration is sending multiple requests for each iteration or is what I understand.
That is, I would expect results after a while, but not multiple results from what I think is just one iteration.
In conclusion I would like to know:
- Why is this happening, is there something I'm not understanding here about functions
async
? - What is the correct way to implement the promise response inside an iterator?