Skip to content

Instantly share code, notes, and snippets.

Created December 20, 2015 01:07
Show Gist options
  • Save anonymous/3aefdde9a6f2eddac698 to your computer and use it in GitHub Desktop.
Save anonymous/3aefdde9a6f2eddac698 to your computer and use it in GitHub Desktop.
var guid = 0;
function getGuid() {
guid += 1;
var id = guid;
console.log('Generated guid', id);
return new Promise(resolve => {
setTimeout(() => {
resolve(id);
}, (Math.random() * 1.5 | 0) * 1000);
});
}
Promise.map = function(collection, method) {
return Promise.all(collection.map(method));
}
Promise.series = function(methods) {
var promise = Promise.resolve();
return Promise.all(methods.map(method => {
return promise = promise.then(method);
}));
}
Promise.mapSeries = function(collection, method) {
return Promise.series(collection.map(item => {
return () => {
return method(item);
};
}));
}
Promise.resolve().then(function() {
// In parallel
return Promise.map(Array.from({length: 10}), getGuid)
.then(function(result) {
console.log(result)
});
}).then(function() {
// In series
return Promise.mapSeries(Array.from({length: 10}), getGuid)
.then(function(result) {
console.log(result)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment