Photo by Nicolas Hoizey on Unsplash
How to concurrently execute an array of asynchronous functions (promises)?
To concurrently execute an array of asynchronous functions, we first create an async function named asyncTask
. This function returns a promise and simulates a task that resolves after a random time or rejects it with an error if a certain condition is met. Here's how you can define the asyncTask
function:
const asyncTask = () => {
const randomTime = Math.floor( Math.random() * 10)
return new Promise((resolve,reject) => {
setTimeout(() => {
if(randomTime < 5) {
reject(`Error ${randomTime}`)
}else {
resolve(randomTime * 1000)
}
}, randomTime *1000)
})
}
If we have to execute this asyncTask
. We will execute it like this.
asyncTask().then((val) => {
console.log(val)
}).catch((error) => {
console.log(error)
})
Let's create an array that contains many asyncTask
which we are going to execute in parallel.
const tasks = [
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask()
]
Next, we can create a function called asyncParallel
that will execute these tasks in parallel and collect the results and errors in arrays. This function takes a callback as an argument, which will provide both the error list and the successful results:
const asyncParallel = (task,callback) => {
const results = [];
const errors = [];
// we are having this complete variable to track that only when all the task
// is complete we will invoke callback.
let completed = 0;
// let's start executing the promises.
tasks.forEach(task => {
task.then((val) => {
results.push(val);
}).catch((error) => {
errors.push(error);
}).finally(() => {
completed++;
if(completed >= tasks.length) {
callback(error,results)
}
})
})
}
Finally, we can execute all the tasks in the tasks
array concurrently using the asyncParallel
function and receive the error and result arrays in the provided callback:
asyncParallel(tasks,(error,result) => {
console.log("Error",error);
console.log("Result",result)
})
This code allows you to execute asynchronous tasks concurrently and collect their results and errors for further processing.
There are also some built-in methods like promise.all
of which can help us execute async tasks in parallel but that will give different results. we will discuss those in some other articles.