Skip to content

Instantly share code, notes, and snippets.

@jaretburkett
Created April 23, 2018 23:23
Show Gist options
  • Save jaretburkett/fc6b973cbda6aca1c626b76e0493cb8a to your computer and use it in GitHub Desktop.
Save jaretburkett/fc6b973cbda6aca1c626b76e0493cb8a to your computer and use it in GitHub Desktop.
Parallel synchronous functions with a common resolve in Node.js
function parallelSync(arrOfSyncFunctions){
return new Promise(async resolve =>{
let numToResolve = arrOfSyncFunctions.length;
let numResolved = 0;
// call after each async function resolves
const resolveOne = () =>{
numResolved++;
if(numResolved >= numToResolve){
// all functions have resolved. Resolve finally
resolve();
}
};
// call all sync functions in parallel
for(let i = 0; i < numToResolve; i++){
(async (i)=>{
await arrOfSyncFunctions[i]();
resolveOne();
})(i)
}
});
}
(async ()=>{
// run syncronus tasks in parallel and wait for all of them to resolve
// each array function will run asynchronusly but will con continue until all are resolved
// you can put as many in the array as you need.
await parallelSync([
async ()=>{
await someSynchronusTask();
await someSynchronusTask2();
},
async ()=>{
await someSynchronusTask3();
await someSynchronusTask4();
}
]);
console.log('parallel sync complete')
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment