How I can chain multiple functions from some class when the first function I'm chaining is static method that returns object instance from the same class?
The purpose of the static method is factory method for setting up strategy pattern, and depending which provider is active it will set the strategy property of the class with different sub class. At the end the static method returns the instance of the base class.
I have one working solution where i first call the static method and hold the object instance in variable reference. After that I'm calling the other function. I like just to compress code in one line with chaining.
// Commented code works
// Provider is the base class
// getActiveProvider is the static method and return Provider class object instance
// findNumbersByIds is non static method
// const provider = await Provider.getActiveProvider();
// return await provider.findNumbersByIds([...]);
// This one not working
return await Provider.getActiveProvider().findNumbersByIds([...]);
I expect with chaining to get the proper result as without chaining.
BR, Igor
TLDR: you're missing parenthesis because await
has lower order of precedence than .
.
The problem isn't with chaining, the problem is you've misused the await
syntax.
Here's an example showing your way of chaining with static and non static methods works fine:
class X {
static create() {
console.log('created');
return new X();
}
y() {
console.log('y');
return this;
}
}
x = X.create().y().y();
Here's an example showing how to do the same correctly when both methods are async:
class X {
static async create() {
console.log('created');
return new X();
}
async y() {
console.log('y');
return this;
}
}
let main = async () => {
x = await (await (await X.create()).y()).y();
};
main();
For your example, to correct syntax you just have to add a single pair of parenthesis:
return (await Provider.getActiveProvider()).findNumbersByIds([...]);