Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active April 24, 2016 17:21
Show Gist options
  • Save ernestlv/a22eb8cafbff0a2f0561cb5ec4d7df38 to your computer and use it in GitHub Desktop.
Save ernestlv/a22eb8cafbff0a2f0561cb5ec4d7df38 to your computer and use it in GitHub Desktop.
prints 1,2,3,4,5,6 using promises within a sequence
// 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());
@ernestlv
Copy link
Author

@ernestlv
Copy link
Author

ernestlv commented Apr 24, 2016

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