Created
December 26, 2023 17:52
-
-
Save cyco130/0a6768dd6a080cc145b6e65549ea8dab to your computer and use it in GitHub Desktop.
Promise test
This file contains hidden or 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
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"); |
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
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:
This gives me better results than the
testFirst
function.