How to run N async tasks in series using JavaScript
To run N asynchronous tasks in series using JavaScript, we can make use of `async/await` and a loop. Here’s an example program that demonstrates how to achieve this:
async function runTasksInSeries(tasks) {
for (let task of tasks) {
await task();
}
}
// Example asynchronous tasks
function asyncTask1() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Async task 1 completed');
resolve();
}, 1000);
});
}
function asyncTask2() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Async task 2 completed');
resolve();
}, 2000);
});
}
function asyncTask3() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Async task 3 completed');
resolve();
}, 1500);
});
}
// Define your tasks in an array
const tasks = [asyncTask1, asyncTask2, asyncTask3];
// Run the tasks in series
runTasksInSeries(tasks)
.then(() => {
console.log('All tasks completed');
})
.catch(error => {
console.error('Error occurred:', error);
});
/* Output:-
"Async task 1 completed"
"Async task 2 completed"
"Async task 3 completed"
"All tasks completed"
*/
In this example, we have three asynchronous tasks (`asyncTask1`, `asyncTask2`, `asyncTask3`) that simulate some asynchronous operations using `setTimeout`. The `runTasksInSeries` function takes an array of tasks as input and runs them in series using a `for` loop and `await`. Each task is awaited, meaning the next task won't start until the previous one has completed.
We can modify the example by adding or removing tasks from the `tasks` array to run a different number of asynchronous tasks in series.
Hope this helps. Have a nice day ahead 😁