Skip to content

Instantly share code, notes, and snippets.

@tobius
Created March 1, 2018 18:51
Show Gist options
  • Save tobius/b88f3719d458d12e09f1d4173b8119e3 to your computer and use it in GitHub Desktop.
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).
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));
@tobius
Copy link
Author

tobius commented Mar 1, 2018

screen shot 2018-03-01 at 1 46 35 pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment