Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active April 25, 2016 00:38
Show Gist options
  • Save ernestlv/7745b8c514f19a01f2b021e9064923ff to your computer and use it in GitHub Desktop.
Save ernestlv/7745b8c514f19a01f2b021e9064923ff to your computer and use it in GitHub Desktop.
promise = v => (new Promise(r => setTimeout(x => r(v), ((Math.random() * (10 - 1)) + 1 | 0) * 1000)));
//execs all promises in parallel but prints numbers randomly
[promise(1),promise(2),promise(3),promise(4),promise(5),promise(6)].forEach(function(p) {
return p.then(v => console.log(v));
}, Promise.resolve());
//still execs promises in parallel and uses a sequence to print numbers in order
[promise(1),promise(2),promise(3),promise(4),promise(5),promise(6)].reduce(function(sequence, p) {
// Add these actions to the end of the sequence
var waitForPromise = sequence.then(x => p);
return waitForPromise.then(v => console.log(v));
}, Promise.resolve());
//using a map is simple!:
[1,2,3,4,5,6].map(promise).reduce(function(sequence, p) {
// Add these actions to the end of the sequence
var waitForPromise = sequence.then(x => p);
return waitForPromise.then(v => console.log(v));
}, Promise.resolve());
//variant (waits till all promises are resolved)
Promise.all([1,2,3,4,5,6].map(promise)).then(i => i.forEach(v => console.log(v)))
//or if order not matter:
[1,2,3,4,5,6].map(promise).forEach(p => p.then(v => console.log(v)));
@ernestlv
Copy link
Author

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