Waiting For Async Function To Complete Inside Map
Solution 1:
Solution
asyncfunctionqueueAsyncFns(fns) {
const values = [];
await fns.reduce((previous, current, index, array) => {
const thenable = index === 1 ? previous() : previous;
return thenable.then(value => {
values.push(value);
return index === array.length - 1 ? current().then(value => values.push(value)) : current();
});
});
return values;
}
Example
const anArray = [1, 2, 3];
const doSomething = async (id) => awaitfetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(res => res.json());
queueAsyncFns(anArray.map((val) =>() =>doSomething(val))).then((val) =>console.log(val));
The above function should solve your issue. Here's a brief overview of what it does:
queueAsyncFns
accepts an array of functions that returns the result of calling an async function. This array is reduced by calling each function and returning the Promise to the next call of the reducer. With each iteration the value of the async call is accumulated into an array called values
which is returned after all items have been iterated through.
The accurate behaviour of the function can be determined visually by looking at the waterfall graph when running the example. You can see each network call is only made after the previous one has been completed.
Solution 2:
If you want to wait for someAsyncFunctionOnObj(obj1) to finish before doing the same but with the next object (obj2, obj3, ...), I think you have to chain your promises:
var promises = arrayOfObjects.map(obj =>someAsyncFunctionOnObj(obj));
await promises.reduce((m, o) => m.then(() => o), Promise.resolve());
Solution 3:
(asyncfunction() {
asyncfunctionexecuteSequentially() {
const tasks = [1,2]
const total = []
for (const fn of tasks) {
const res = awaitfetch(endpoint);
const res2 = await res.json();
console.log(res2[0]);
total.push(...res2);
}
return total;
}
const res = awaitexecuteSequentially();
console.log(res);
})();
Post a Comment for "Waiting For Async Function To Complete Inside Map"