Skip to content

Instantly share code, notes, and snippets.

@ra100
Last active January 12, 2018 18:42
Show Gist options
  • Save ra100/c0917b3aee0499c903b4a9dc340edb7d to your computer and use it in GitHub Desktop.
Save ra100/c0917b3aee0499c903b4a9dc340edb7d to your computer and use it in GitHub Desktop.
How to simply delay Promises generated from array executed in Promise.all.
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