Last active
April 24, 2016 17:21
-
-
Save ernestlv/a22eb8cafbff0a2f0561cb5ec4d7df38 to your computer and use it in GitHub Desktop.
prints 1,2,3,4,5,6 using promises within a sequence
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
// serialize asynchronous code | |
// Start off with a promise that always resolves | |
var sequence = Promise.resolve(); | |
// Loop | |
[1,2,3,4,5,6].forEach(function(v) { | |
// Add these actions to the end of the sequence | |
sequence = sequence.then(function() { | |
return new Promise(r => setTimeout(x => r(v), ((Math.random() * (10 - 1)) + 1 | 0) * 1000)); | |
}).then(v => console.log(v)); | |
}); | |
//or | |
[1,2,3,4,5,6].reduce(function(sequence, v) { | |
// Add these actions to the end of the sequence | |
sequence = sequence.then(function() { | |
return new Promise(r => setTimeout(x => r(v), ((Math.random() * (10 - 1)) + 1 | 0) * 1000)); | |
}).then(v => console.log(v)); | |
}, Promise.resolve()); |
very inefficient since the timeout is created within the sequence. see https://gist.github.com/ernestlv/7745b8c514f19a01f2b021e9064923ff
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