【问题标题】:At an object's instantiation time how does one handle best the asynchronous initialization of one of its properties?在对象的实例化时,如何最好地处理其属性之一的异步初始化?
【发布时间】:2020-10-04 09:43:34
【问题描述】:

我以前从未创建过 Javascript 模块/库,所以这对我来说有点新鲜,所以对于我不知道谷歌搜索什么表示歉意。

我正在创建一个库,该库将保存来自用户提供的 URL 的信息。我想解析 URL 的路径(域之后的部分)并保留 URL 响应提供的标头值。

这是基本的,但这是我目前所拥有的:

function Link(someURL) {
  this.url = someURL;
  this.urlPath = "";
  this.uuid = "";

  this.getPath = function (someURL) {
    // do regexp parsing and return everything after the domain
  };

  this.getUUID = function (someURL) {
    // fetch the URL and return what is in the response's "uuid" header
  }
}

理想情况下,我希望模块在构建时自动获取所有信息:

var foo = new Link("http://httpbin.org/response-headers?uuid=36d09ff2-4b27-411a-9155-e82210a100c3")
console.log(foo.urlPath);  // should return "uuid"
console.log(foo.uuid);  // should return the contents in the "uuid" header in the response

如何确保this.urlPaththis.uuid 属性与this.url 一起初始化?理想情况下,我只会获取一次 URL(以防止目标服务器限制速率)。

【问题讨论】:

  • 您在课堂、图书馆结构或两者中需要帮助吗?
  • 而不是直接导出Link 类或工厂,您应该导出一个配置函数,让用户提供所有必要的信息。然后,此配置函数将返回 Link 对象的工厂,确保已提供所有配置
  • 始终尽量保持类/构造函数实现和初始化的占用空间尽可能小。在模块范围内尽可能多地实现类的相关计算/帮助器功能,但(如果可能的话)不直接连接到类/构造函数。 Link 类的奖励:使必要的 url 部分的计算变得惰性(第一次需要时计算)但记住(保存惰性计算结果/一次计算)。
  • @PeterSeliger 这就是我正在尝试做的,但就像我说的,我对此很陌生。一旦 urlPath 和 uuid 被解析和检索,它们就不需要再被弄乱了,但仍然不确定如何初始化这些属性。

标签: javascript node.js asynchronous initialization instantiation


【解决方案1】:

经过多次反复试验,我最终做了类似这样的事情:

class Link {
  constructor (url_in) {
    const re = RegExp("^https://somedomain.com\/(.*)$");
    this.url = re[0];
    this.linkPath = re[1];
  }

  async getUUID() {
    const res = await fetch("https://fakedomain.com/getUUID?secret=" + this.linkPath);
    this.uuid = res.uuid;
  }

  async getJSON() {
    const res = await fetch("https://fakedomain.com/getJSON?uuid=" + this.uuid);
    this.json = await res.json();
  }

  async initialize() {
    await this.getUUID();
    await this.getJSON();
  }
}


const someLinkData = new Link("https://reallydumbdomain.com/2020/10/4/blog");
someLinkData.initialize()
  .then(function() {
    console.log(this.json); // this now works
  });

我认为未来的迭代将需要我使用 initialize 函数发送一个承诺,但现在,这可行。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
相关资源
最近更新 更多