Created
March 2, 2024 06:08
-
-
Save satyam4p/571ae36093ba6feb10ff4913e01f5828 to your computer and use it in GitHub Desktop.
Snippet for Running async tasks in parallel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**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