Functional JavaScript: Resolving Promises Sequentially

Joel Thoms
Jan 4, 2017 · 4 min read
// some dummy urls to resolve
const urls = ['/url1', '/url2', '/url3']

// convert each url to a function that returns an ajax call
const funcs = urls.map(url => () => $.ajax(url))
Promise.resolve()
.then(x => funcs[0]()) // resolve func[0]
.then(x => funcs[1]()) // resolve func[1]
.then(x => funcs[2]()) // resolve func[2]
// start our promise off with an empty array. this becomes all.
Promise.resolve([])
// all is the array we will append each result to.
.then(all => {
return funcs[0]().then(result => {
// concat the resolved promise result to all
return all.concat(result)
})
})
Promise.resolve([])
.then(all => funcs[0]().then(result => all.concat(result)))
Promise.resolve([])
.then(all => funcs[0]().then(Array.prototype.concat.bind(all)))
Promise.resolve([])
.then(x => funcs[0]().then(Array.prototype.concat.bind(x)))
.then(x => funcs[1]().then(Array.prototype.concat.bind(x)))
.then(x => funcs[2]().then(Array.prototype.concat.bind(x)))

Whenever you need to transform a list into a single object, consider using reduce.

Our promiseSerial function should take an array of factory functions (that each return a Promise) and reduce them into the single Promise chain expressed above.

const promiseSerial = funcs =>
funcs.reduce((promise, func) => ???, Promise.resolve([]))
const promiseSerial = funcs =>
funcs.reduce((promise, func) =>
promise.then(result =>
func().then(Array.prototype.concat.bind(result))),
Promise.resolve([]))

Related Articles

HackerNoon.com

how hackers start their afternoons.

Joel Thoms

Written by

Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!

HackerNoon.com

how hackers start their afternoons.