Created
November 4, 2017 19:04
-
-
Save snoj/b024a139e9aaffb7015da317d3f3a82a to your computer and use it in GitHub Desktop.
Promise.series
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
//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