Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created March 2, 2024 06:08
Show Gist options
  • Save satyam4p/571ae36093ba6feb10ff4913e01f5828 to your computer and use it in GitHub Desktop.
Save satyam4p/571ae36093ba6feb10ff4913e01f5828 to your computer and use it in GitHub Desktop.
Snippet for Running async tasks in parallel
/**generates async tasks */
function asyncTask() {
return new Promise((resolve, reject) => {
let val = Math.floor(Math.random() * 10);
if (val > 5) {
resolve(val);
} else {
reject(val);
}
});
}
let taskList = [
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
asyncTask(),
];
/**function for running all async tasks parallely and appending their result/error in array */
function executeParallelTasks(taskList, callback) {
let results = [];
let errors = [];
let completed = 0;
taskList.forEach((task) => {
task
.then((res) => {
results.push(res);
})
.catch((err) => {
errors.push(err);
})
.finally(() => {
completed = completed + 1;
if (completed >= taskList.length) {
callback(results, errors);
}
});
});
}
/**call the parallel execution tasks function with callback */
executeParallelTasks(taskList, (results, errors) => {
console.log("results:: ", results);
console.log("errors:: ", errors);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment