Last active
October 26, 2017 21:50
-
-
Save loretoparisi/bb074191cdb8aa1f002066d9de292c51 to your computer and use it in GitHub Desktop.
JavaScript Promise Waterfall
This file contains 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
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