Skip to content

Instantly share code, notes, and snippets.

@joelnet
Last active March 8, 2024 10:04
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save joelnet/b286721a933e7e410120a8a2866dbcc8 to your computer and use it in GitHub Desktop.
Save joelnet/b286721a933e7e410120a8a2866dbcc8 to your computer and use it in GitHub Desktop.
/*
* promiseSerial resolves Promises sequentially.
* @example
* const urls = ['/url1', '/url2', '/url3']
* const funcs = urls.map(url => () => $.ajax(url))
*
* promiseSerial(funcs)
* .then(console.log)
* .catch(console.error)
*/
const promiseSerial = funcs =>
funcs.reduce((promise, func) =>
promise.then(result => func().then(Array.prototype.concat.bind(result))),
Promise.resolve([]))
// some url's to resolve
const urls = ['/url1', '/url2', '/url3']
// convert each url to a function that returns a promise
const funcs = urls.map(url => () => $.ajax(url))
// execute Promises in serial
promiseSerial(funcs)
.then(console.log.bind(console))
.catch(console.error.bind(console))
@jcubic
Copy link

jcubic commented Aug 1, 2017

.then(console.log) will not work because log require console as context, you need to use console.log.bind(console)

@joelnet
Copy link
Author

joelnet commented Aug 17, 2017

Oops. Updated! Thanks!

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