Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, fn) => {
    let p = new Promise(fn);
    chain.then(p);
    return p;
  },
  Promise.resolve()
);

Ps. any other tips are more than welcomed.

like image 338
ddibiase Avatar asked Nov 13 '16 23:11

ddibiase


People also ask

Can promises be chained?

Example 2: Chaining the Promise with then() Promise resolved You can call multiple functions this way. In the above program, the then() method is used to chain the functions to the promise. The then() method is called when the promise is resolved successfully. You can chain multiple then() methods with the promise.

What is chaining of promise?

Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task.

What is promise chaining give an example?

Chaining after a catch It's possible to chain after a failure, i.e. a catch , which is useful to accomplish new actions even after an action failed in the chain. Read the following example: new Promise((resolve, reject) => { console. log("Initial"); resolve(); }) .

Can promises be nested?

Nested Promise: Promises give you return statements and error throwing, which you lose with continuation-passing style. A nested promise is when you call child promise inside . then of parent promise and this go-on.


2 Answers

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: https://stackoverflow.com/a/30823708/4052701

like image 59
TiagoLr Avatar answered Nov 15 '22 04:11

TiagoLr


What about ES7 async/await? Strange/old bind(this) in your code, but kept to not confuse with your example.

async function x() {
    try {
        await this.connectDatabase.bind(this);
        await this.connectServer.bind(this);
        await this.listen.bind(this);
    } catch(e) {
        throw e;
    }
}

or more generic

async function () {
    for (let item of yourArray) {
        try {
            await item.bind(this); //strange bind of your code.
        } catch(e) {
            throw e;
        }
    }
}
like image 34
Niels Steenbeek Avatar answered Nov 15 '22 02:11

Niels Steenbeek