ddibiase ddibiase - 26 days ago 10
Node.js Question

Chaining promises in a waterfall

I've been playing around with a few different ways of chaining a collection of functions and can't seem to find one I particularly like. The following is the last one I settled on but am still not keen on it.

Can someone suggest a cleaner and more concise pattern? I don't want to opt for Async.js or a library.

[
this.connectDatabase.bind(this),
this.connectServer.bind(this),
this.listen.bind(this)
].reduce(
(chain, task) => {
let promise = new Promise(
(resolve, reject) => {
task(resolve, reject);
}
);
return chain ? chain.then(promise) : promise;
},
null
);


Ps. any other tips are more than welcomed.

Answer

Found this solution on stackoverflow on how you can chain promises dynamically:

iterable.reduce((p, fn) => p.then(fn), Promise.resolve())

The complete post is here: http://stackoverflow.com/a/30823708/4052701