Created
March 1, 2018 18:51
-
-
Save tobius/b88f3719d458d12e09f1d4173b8119e3 to your computer and use it in GitHub Desktop.
An example of how differently `Promise.all(arr.map(iteratee))` behaves when iteratee returns a synchronous result (value) versus an asynchronous result (promise).
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
const chalk = require('chalk'); | |
/** | |
* sleep given number of milliseconds | |
* | |
* @param {Integer} ms | |
* @return {Void} | |
*/ | |
function sleep(ms) { | |
const start = new Date().getTime(); | |
for (let i = 0; i < 1e7; i++) { | |
if ((new Date().getTime() - start) > ms) { | |
break; | |
} | |
} | |
} | |
/** | |
* generate a random number up to given max | |
* | |
* @param {Integer} max | |
* @return {Integer} | |
*/ | |
function random(max) { | |
return Math.floor(Math.random() * Math.floor(max)); | |
} | |
/** | |
* perform a randomly timed synchronous task (up to 2000ms) | |
* | |
* @param {Integer} index | |
* @return {Integer} index | |
*/ | |
function iterateSync(index) { | |
console.log(chalk.yellow(`sync started, index ${index}`)); | |
const delay = random(2000); | |
sleep(delay); | |
console.log(chalk.yellow(`sync complete, index ${index} took ${delay}ms`)); | |
return index; | |
} | |
/** | |
* perform a randomly timed asynchronous task (up to 2000ms) | |
* | |
* @param {Integer} index | |
* @return {Promise} `.then(index)` | |
*/ | |
async function iterateAsync(index) { | |
console.log(chalk.green(`async started, index ${index}`)); | |
return new Promise((r) => { | |
const delay = Math.floor(Math.random() * Math.floor(2000)); | |
setTimeout(() => { | |
console.log(chalk.green(`async complete, index ${index} took ${delay}ms`)); | |
r(index); | |
}, delay); | |
}); | |
} | |
const indexes = [1, 2, 3, 4, 5]; | |
syncItems = Promise.all(indexes.map(iterateSync)); | |
asyncItems = Promise.all(indexes.map(iterateAsync)); |
Author
tobius
commented
Mar 1, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment