Skip to content

Instantly share code, notes, and snippets.

@snoj
Created November 4, 2017 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snoj/b024a139e9aaffb7015da317d3f3a82a to your computer and use it in GitHub Desktop.
Save snoj/b024a139e9aaffb7015da317d3f3a82a to your computer and use it in GitHub Desktop.
Promise.series
//Run an array of values in series.
//Non-functions are wrapped in Promise.resolve().
//Functions are passed to the Promise constructor. (eg new Promise(myFunction);)
//Series order starts from 0.
Promise.series = function PromiseSeries(promises) {
function assignTo(o, k) {
return function(v) {
o[k] = v;
return v;
};
}
function interator(v, i, arr, varr, gr, gx) {
if(i == arr.length)
return gr(varr);
var p;
if(typeof v == 'function') {
p = (new Promise(v));
} else {
p = Promise.resolve(v);
}
p
.then(assignTo(varr, i))
.then(interator.bind(this, arr[i+1], i+1, arr, varr, gr, gx))
.catch(gx);
};
return new Promise(function(resolve, reject) {
var si = promises.length-1;
var varr = new Array(promises.length);
interator(promises[0], 0, promises, varr, resolve, reject);
});
};
//
// Example
//
var series = [1,2,3, function(resolve, reject) { setTimeout(resolve.bind(null, 1337), 5000); }, [Promise.resolve(5)]];
Promise.series(series).then(console.log);
> [1, 2, 3, 1337, [Promise]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment