Skip to content

Instantly share code, notes, and snippets.

@cyco130
Created December 26, 2023 17:52
Show Gist options
  • Save cyco130/0a6768dd6a080cc145b6e65549ea8dab to your computer and use it in GitHub Desktop.
Save cyco130/0a6768dd6a080cc145b6e65549ea8dab to your computer and use it in GitHub Desktop.
Promise test
function fnThatReturnsPromiseOrValue() {
const random = Math.random();
if (random > 0.5) {
return Promise.resolve(random);
} else {
return random;
}
}
async function naive() {
let total = 0;
for (let i = 0; i < 1000_000; i++) {
total += await fnThatReturnsPromiseOrValue();
}
console.log(total);
}
async function testFirst() {
let total = 0;
for (let i = 0; i < 1000_000; i++) {
let result = fnThatReturnsPromiseOrValue();
if (result instanceof Promise) {
result = await result;
}
total += result;
}
console.log(total);
}
console.time("naive");
await naive();
console.timeEnd("naive");
console.time("testFirst");
await testFirst();
console.timeEnd("testFirst");
@cyco130
Copy link
Author

cyco130 commented Dec 27, 2023

Hi @jainmohit2001!

Sure, running all promises in parallel would indeed be faster and is the better idea for this particular example.

What I was trying to point out the difference between just awaiting and checking first to see if it's a promise and only awaiting if it is. Doing it a million times was only to multiply the effect to have meaningful numbers :)

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