Created
April 23, 2018 23:23
-
-
Save jaretburkett/fc6b973cbda6aca1c626b76e0493cb8a to your computer and use it in GitHub Desktop.
Parallel synchronous functions with a common resolve in Node.js
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
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