Skip to content

Instantly share code, notes, and snippets.

@Leglaw
Last active May 25, 2023 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leglaw/0b5f973902c0b75a6552eb2f44155603 to your computer and use it in GitHub Desktop.
Save Leglaw/0b5f973902c0b75a6552eb2f44155603 to your computer and use it in GitHub Desktop.
Await vs Promise.all concurrency comparison
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();
@Leglaw
Copy link
Author

Leglaw commented May 24, 2023

Running the above produces the following output:

testPromiseAll: 3.005s
MAIN: resultPromise [
  'RESULT: Promise first',
  'RESULT: Promise second',
  'RESULT: Promise third',
  'RESULT: Promise fourth'
]
testMultipleAwaits: 7.005s
MAIN: resultAwait [
  'RESULT: await first',
  'RESULT: await second',
  'RESULT: await third',
  'RESULT: await fourth'
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment