Execute async functions in Series
Implement a function that takes a list of async functions as input and executes them in a series that is one at a time. The next task is executed only when the previous task is completed.
const asyncSeriesExecuter = async (promises) => {
for (let promise of promises) {
try {
const response = await promise;
console.log(response);
} catch (e) {
console.log(e);
}
}
};
Example
const asyncSeriesExecuter = async (promises) => {
for (let promise of promises) {
try {
const response = await promise;
console.log(response);
} catch (e) {
console.log(e);
}
}
};
const asyncTask = (time) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Completing in " + String(time) + "s");
}, 100 * time);
});
};
const promises = [
asyncTask(3),
asyncTask(1),
asyncTask(7),
asyncTask(2),
asyncTask(5),
];
asyncSeriesExecuter(promises);
// Output:
Completing in 3s
Completing in 1s
Completing in 7s
Completing in 2s
Completing in 5s