Last active
January 12, 2018 18:42
-
-
Save ra100/c0917b3aee0499c903b4a9dc340edb7d to your computer and use it in GitHub Desktop.
How to simply delay Promises generated from array executed in Promise.all.
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
const time = Date.now(); | |
const data = ["a", "b", "c", "d"]; | |
// this is actually what I want | |
const delay = (cb, timeout) => | |
new Promise(resolve => setTimeout(() => resolve(cb()), timeout)); | |
// this simulates async call network/io operation | |
const fakeAsync = log => | |
new Promise(resolve => { | |
console.log(`started ${log}`, Date.now() - time); | |
setTimeout(() => { | |
console.log(`ended ${log}`, Date.now() - time); | |
return resolve(log); | |
}, Math.floor(Math.random() * 1000)); | |
}); | |
console.log("preparation", Date.now() - time); | |
// and this is how to execute | |
const promises = data.map((d, index) => delay(() => fakeAsync(d), 100 * index)); | |
console.log("started all", Date.now() - time); | |
Promise.all(promises).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment