Created
January 10, 2020 08:34
-
-
Save sashee/13c59ba3b3b993935465cf8a71a2e268 to your computer and use it in GitHub Desktop.
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script> | |
console.log = (msg) => document.body.innerText += `${msg}\n`; | |
// utility function for sleeping | |
const sleep = (n) => new Promise((res) => setTimeout(res, n)); | |
(async () => { | |
{ | |
console.log("\nsync reduce"); | |
const arr = [1, 2, 3]; | |
const syncRes = arr.reduce((memo, e) => { | |
return memo + e; | |
}, 0); | |
console.log(syncRes); | |
// 6 | |
} | |
await sleep(200); // without sleeping first the async reduce takes a lot more time | |
{ | |
console.log("\nasync reduce"); | |
const arr = [1, 2, 3]; | |
const startTime = new Date().getTime(); | |
const asyncRes = await arr.reduce(async (memo, e) => { | |
await sleep(10); | |
return (await memo) + e; | |
}, 0); | |
console.log(asyncRes); | |
// 6 | |
console.log(`Took ${new Date().getTime() - startTime} ms`); | |
// Took 11-13 ms | |
} | |
{ | |
console.log("\nasync reduce with await memo first"); | |
const arr = [1, 2, 3]; | |
const startTime = new Date().getTime(); | |
const asyncRes = await arr.reduce(async (memo, e) => { | |
await memo; | |
await sleep(10); | |
return (await memo) + e; | |
}, 0); | |
console.log(asyncRes); | |
// 6 | |
console.log(`Took ${new Date().getTime() - startTime} ms`); | |
// Took 34-38 ms | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment