Skip to content

Instantly share code, notes, and snippets.

@gildas
Created February 13, 2017 00:52
Show Gist options
  • Save gildas/d12a522d5294b04db1ca78274e3c9db7 to your computer and use it in GitHub Desktop.
Save gildas/d12a522d5294b04db1ca78274e3c9db7 to your computer and use it in GitHub Desktop.
execute promises in series
// Promise returning functions to execute
function doFirstThing(){ return Promise.resolve(1); }
function doSecondThing(res){ return Promise.resolve(res + 1); }
function doThirdThing(res){ return Promise.resolve(res + 2); }
function lastThing(res){ console.log("result:", res); }
var fnlist = [ doFirstThing, doSecondThing, doThirdThing, lastThing];
// Execute a list of Promise return functions in series
function pseries(list) {
var p = Promise.resolve();
return list.reduce(function(pacc, fn) {
return pacc = pacc.then(fn);
}, p);
}
pseries(fnlist);
// result: 4
@gildas
Copy link
Author

gildas commented Feb 13, 2017

@gildas
Copy link
Author

gildas commented Feb 13, 2017

Don't forget to pass promise factories not promises.
I.e.: This won't work:

pseries(promise1(), promise2(), ...])

Whereas this will:

pseries(promise1, promise2, ...])

@gildas
Copy link
Author

gildas commented Feb 13, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment