Last active
April 25, 2016 00:38
-
-
Save ernestlv/7745b8c514f19a01f2b021e9064923ff to your computer and use it in GitHub Desktop.
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
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))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
inspired by: http://www.html5rocks.com/en/tutorials/es6/promises/#toc-parallelism-sequencing