Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Last active October 26, 2017 21:50
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 loretoparisi/bb074191cdb8aa1f002066d9de292c51 to your computer and use it in GitHub Desktop.
Save loretoparisi/bb074191cdb8aa1f002066d9de292c51 to your computer and use it in GitHub Desktop.
JavaScript Promise Waterfall
function isPromise(obj) {
return obj && typeof obj.then === 'function';
}
function waterfall(list) {
// malformed argument
list = Array.prototype.slice.call(list);
if (!Array.isArray(list) // not an array
|| typeof list.reduce !== "function" // update your javascript engine
|| list.length < 1 // empty array
) {
return Promise.reject("Array with reduce function is needed.");
}
if (list.length == 1) {
if (typeof list[0] != "function")
return Promise.reject("First element of the array should be a function, got " + typeof list[0]);
return Promise.resolve(list[0]());
}
return list.reduce(function(l, r){
// first round
// execute function and return promise
var isFirst = (l == list[0]);
if (isFirst) {
if (typeof l != "function")
return Promise.reject("List elements should be function to call.");
var lret = l();
if (!isPromise(lret))
return Promise.reject("Function return value should be a promise.");
else
return lret.then(r);
}
// other rounds
// l is a promise now
// priviousPromiseList.then(nextFunction)
else {
if (!isPromise(l))
Promise.reject("Function return value should be a promise.");
else
return l.then(r);
}
});
}
var promises= [()=>{
return new Promise((r,_) => r(0))
} ].concat([...new Array(3).keys()].map((item,index) => (res)=>{
res++;
return new Promise((r,_) => r(res))
}
))
waterfall(promises) .then(res=> console.log(res)) .catch((err) => console.error(err) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment