在 javascript es6 中链接静态和非静态方法

Chaining static and non static method in javascript es6

当我链接的第一个函数是来自同一个 class 的 returns 对象实例的静态方法时,我如何链接来自某些 class 的多个函数?

静态方法的目的是设置策略模式的工厂方法,根据激活的提供者,它将设置 class 的策略 属性 与不同的子 class.最后静态方法 returns 基础实例 class.

我有一个可行的解决方案,我首先调用静态方法并将对象实例保存在变量引用中。之后我调用另一个函数。我喜欢用链接将代码压缩成一行。

// 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([...]);

我希望通过链接获得与没有链接时一样的正确结果。

BR,伊戈尔

TLDR:您缺少括号,因为 await 的优先级低于 .

问题不在于链接,问题在于您误用了 await 语法。

这是一个示例,展示了您使用静态和非静态方法进行链接的方式工作正常:

class X {
  static create() {
    console.log('created');
    return new X();
  }
  
  y() {
    console.log('y');
    return this;
  }
}

x = X.create().y().y();

下面是一个示例,展示了当两种方法都是异步时如何正确地执行相同操作:

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();

对于您的示例,要更正语法,您只需添加一对括号:

return (await Provider.getActiveProvider()).findNumbersByIds([...]);