Currently, I have an array that needs to be mapped. Inside the mapping function, there is an asynchronous function being called, which conducts an asynchronous request and returns a promise using request-promise
.
My intention was for the first item in the array to be mapped, then perform the request, followed by the second item repeating the same process. However, this sequence is not occurring as expected in my current scenario.
Here is the function in question:
const fn = async() => {
const array = [0, 1, 2];
console.log('begin');
await Promise.all(array.map(item => anAsyncFunction(item)));
console.log('finished');
return;
}
The anAsyncFunction
looks like this:
const anAsyncFunction = async item => {
console.log(`looping ${item}`);
const awaitingRequest = await functionWithPromise(item);
console.log(`finished looping ${item}`);
return awaitingRequest;
}
And here's where the request is being made in functionWithPromise
:
const functionWithPromise = async (item) => {
console.log(`performing request for ${item}`);
return Promise.resolve(await request(`https://www.google.com/`).then(() => {
console.log(`finished performing request for ${item}`);
return item;
}));
}
Looking at the console logs I currently have:
begin
looping 0
performing request for 0
looping 1
performing request for 1
looping 2
performing request for 2
finished performing request for 0
finished looping 0
finished performing request for 1
finished looping 1
finished performing request for 2
finished looping 2
finished
However, what I was aiming for is:
begin
looping 0
performing request for 0
finished performing request for 0
finished looping 0
looping 1
performing request for 1
finished performing request for 1
finished looping 1
looping 2
performing request for 2
finished performing request for 2
finished looping 2
finished
Although this workflow pattern usually suffices, it appears that I might be receiving some invalid results from the request call due to possibly making too many requests simultaneously.
If anyone has suggestions on more effective methods to achieve my desired outcome, please do share.