【问题标题】:Chaining static and non static method in javascript es6在javascript es6中链接静态和非静态方法
【发布时间】:2019-09-04 14:59:44
【问题描述】:

当我链接的第一个函数是从同一类返回对象实例的静态方法时,我如何从某个类链接多个函数?

静态方法的目的是设置策略模式的工厂方法,根据哪个提供者处于活动状态,它将设置具有不同子类的类的策略属性。最后静态方法返回基类的实例。

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

// 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,伊戈尔

【问题讨论】:

  • 请在问题中插入类声明(至少,它的相关部分),以帮助我们识别,发生了什么!另请阅读:How to create a Minimal, reproducible example
  • 我猜你在找return (await Provider.getActiveProvider()).findNumbersByIds([...]);

标签: javascript class static chaining


【解决方案1】:

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

【讨论】:

  • Tnx。我知道 await 搞砸了一些东西,但我不确定括号是否会对我有所帮助。
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 2016-08-07
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多