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.
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.
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.
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(); }) .
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.
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
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With