Created
March 23, 2019 22:24
-
-
Save micahriggan/7beb9e3e88f5a2eb140780b39e1158cd to your computer and use it in GitHub Desktop.
Adding async values that are fetched in parallel vs serially
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
function randomNumber() { | |
const rand = Math.random() * 100; | |
return new Promise(resolve => setTimeout(() => { | |
resolve(rand) | |
}, 1000)) | |
} | |
async function addExampleSerial() { | |
console.time('add-serial'); | |
const number1 = await randomNumber(); | |
const number2 = await randomNumber(); | |
const result = number1 + number2; | |
console.timeEnd('add-serial'); | |
console.log('serial result: ', result); | |
} | |
async function addExampleParallel() { | |
console.time('add-parallel'); | |
const [number1, number2] = await Promise.all([randomNumber(), randomNumber()]); | |
const result = number1 + number2; | |
console.timeEnd('add-parallel'); | |
console.log('parallel result: ', result); | |
} | |
async function test() { | |
await addExampleSerial(); | |
await addExampleParallel(); | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment