Skip to content

Instantly share code, notes, and snippets.

@jabis
Last active September 2, 2016 12:18
Show Gist options
  • Save jabis/f8f3efe404c06e62eaead7b256bb91d6 to your computer and use it in GitHub Desktop.
Save jabis/f8f3efe404c06e62eaead7b256bb91d6 to your computer and use it in GitHub Desktop.
MooTools Promise.Series map/reduce
(function(){
this.Promise = new Class({
Implements: Class.Thenable,
initialize: function(promise) {
if (typeof promise !== 'function')
throw new TypeError('Promise accepts only a function constructor!');
try {
promise(this.resolve.bind(this), this.reject.bind(this));
} catch (e) {
this.reject(e);
}
}
});
this.Promise.Series = new Class({
Implements: Class.Thenable,
initialize: function(promises) {
if (typeOf(promises) != "array")
throw new TypeError('Promise Series accepts only an array of functions returning promises as constructor!');
var ret = new Promise(function(fn, err) {}).resolve(null);
var results = [];
return promises.reduce(function(result, promise, index) {
return result.then(function() {
return promise().then(function(val) {
results[index] = val;
});
});
}, ret).then(function() {
return results;
});
}
});
})();
//USAGE:
new Promise.Series([
function(){
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log('a resolving.')
resolve('a');
},3000);
})
},
function(){
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log('b resolving.')
resolve('b');
},1000);
})
}
]).then(function(results){
console.log('Results in execution order:',results);
}).catch(function(e){
console.error('Rejection based on:', e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment