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");
@jainmohit2001
Copy link

Hey @cyco130.
Saw your post on Twitter which led me to this code.

I was wondering what would happen if we create an array of promises and await them all using Promise.all(). We would have to sacrifice the memory to store the promise and results in an array.

Example:

async function testPromiseAll() {
  let total = 0;
  let promises = [];
  for (let i = 0; i < 1000_000; i++) {
    promises.push(fnThatReturnsPromiseOrValue());
  }

  const results = await Promise.all(promises);
  for(let i = 0; i < results.length; i++){
      total += results[i];
  }

  console.log(total);
}

This gives me better results than the testFirst function.

@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