Last active
October 1, 2018 21:45
-
-
Save flockonus/1c173ef70d0702ac96f29e0961f007fb to your computer and use it in GitHub Desktop.
Example of concurrency using Javascript promises + await
This file contains 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
const sleep = (seconds) => { | |
return new Promise((accept) => | |
setTimeout(accept, seconds * 1000, `slept ${seconds}`), | |
); | |
}; | |
async function execParallel() { | |
console.log(new Date(), 'starting'); | |
// promises will execute concurrently, so that execution time = slowest one (not the sum) | |
const out = await Promise.all([sleep(5), sleep(5), sleep(5)]); | |
console.log(new Date(), 'ended:', out); | |
} | |
execParallel().then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment