Created
January 10, 2020 08:43
-
-
Save sashee/94a42020c3b903f1415a70f41af26210 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 forEach"); | |
const arr = [1, 2, 3]; | |
arr.forEach((i) => { | |
console.log(i); | |
}); | |
// 1 | |
// 2 | |
// 3 | |
console.log("Finished sync"); | |
// Finished sync | |
} | |
{ | |
console.log("\nasync forEach"); | |
const arr = [1, 2, 3]; | |
arr.forEach(async (i) => { | |
await sleep(10 - i); | |
console.log(i); | |
}); | |
console.log("Finished async"); | |
// Finished async | |
// 3 | |
// 2 | |
// 1 | |
} | |
await sleep(20); | |
{ | |
console.log("\ncontrolled forEach"); | |
const arr = [1, 2, 3]; | |
await Promise.all(arr.map(async (i) => { | |
await sleep(10 - i); | |
console.log(i); | |
})); | |
// 3 | |
// 2 | |
// 1 | |
console.log("Finished async"); | |
// Finished async | |
} | |
{ | |
console.log("\nserialized forEach"); | |
const arr = [1, 2, 3]; | |
await arr.reduce(async (memo, i) => { | |
await memo; | |
await sleep(10 - i); | |
console.log(i); | |
}, undefined); | |
// 1 | |
// 2 | |
// 3 | |
console.log("Finished async"); | |
// Finished async | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment