Skip to content

Instantly share code, notes, and snippets.

@bitifet
Last active September 4, 2017 05:41
Show Gist options
  • Select an option

  • Save bitifet/1adece3b3d2f526ce638bbce1ba16bba to your computer and use it in GitHub Desktop.

Select an option

Save bitifet/1adece3b3d2f526ce638bbce1ba16bba to your computer and use it in GitHub Desktop.
Sequential waterfall over array of promisorys.
// Performs sequential waterfall over array of promisorys.
// Following two sentences:
// var P = Promise.all(inArr.map(cbk))
// var P = arrayfall(inArr, cbk)
// ...are pretty much the same.
// Both runs all promises sequentially and returns new promise resolving with
// an array with resolved data (if none rejected).
// But in the former all promises are run as fast as input array is scanned.
// Whereas with arrayfall() promises are executed in sequence: each after
// previous one is resolved (or rejected) even being completely asyncronous.
function arrayfall(inArr, cbk) {
var arr = [];
inArr.map(function(item, i) {
arr[i] = i
? arr[i-1].then(function(data){
arr[i-1] = data; // Release.
return Promise.resolve(cbk(item, i));
})
: Promise.resolve(cbk(item, i))
;
});
return Promise.all(arr);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment