Last active
May 25, 2023 13:40
-
-
Save Leglaw/0b5f973902c0b75a6552eb2f44155603 to your computer and use it in GitHub Desktop.
Await vs Promise.all concurrency comparison
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
async function runTask(seconds, msg) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(`RESULT: ${msg}`); | |
}, seconds * 1000); | |
}); | |
} | |
async function testPromiseAll() { | |
return Promise.all([ | |
runTask(2, 'Promise first'), | |
runTask(1, 'Promise second'), | |
runTask(3, 'Promise third'), | |
runTask(1, 'Promise fourth'), | |
]); | |
} | |
async function testMultipleAwaits() { | |
const result1 = await runTask(2, 'await first'); | |
const result2 = await runTask(1, 'await second'); | |
const result3 = await runTask(3, 'await third'); | |
const result4 = await runTask(1, 'await fourth'); | |
return [ result1, result2, result3, result4 ]; | |
} | |
async function runTest(fn) { | |
const label = fn.name; | |
console.time(label); | |
const results = await fn(); | |
console.timeEnd(label); | |
console.log(`${label} results`, results); | |
} | |
async function runTests() { | |
return Promise.all([ | |
runTest(testPromiseAll), | |
runTest(testMultipleAwaits) | |
]); | |
} | |
function main() { | |
runTests(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running the above produces the following output: