Javascript 在一个对象上';s实例化时间如何最好地处理其属性之一的异步初始化?

Javascript 在一个对象上';s实例化时间如何最好地处理其属性之一的异步初始化?,javascript,node.js,asynchronous,initialization,instantiation,Javascript,Node.js,Asynchronous,Initialization,Instantiation,我以前从未创建过Javascript模块/库,所以这对我来说有点陌生,所以我为我不知道谷歌应该做什么而道歉 我正在创建一个库,它将保存来自用户提供的URL的信息。我想解析URL的路径(位于域之后的部分),并保留URL响应提供的头值 这是基本的,但以下是我到目前为止的情况: function Link(someURL) { this.url = someURL; this.urlPath = ""; this.uuid = ""; this

我以前从未创建过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.urlPath
this.uuid
属性与
this.url
一起初始化?理想情况下,我只获取URL一次(以防止目标服务器限制速率)。

经过多次尝试和错误后,我最终做了类似的事情:

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
函数的承诺,但现在,这是可行的。

您需要类、库结构或两者的帮助吗?而不是直接导出
链接
类或工厂,您应该导出一个配置函数,让用户提供所有必要的信息。然后,此配置函数将返回
链接
对象的工厂,确保所有配置都已提供。请尽量保持类/构造函数实现和初始化的占用空间尽可能小。在模块范围内尽可能多地实现类的相关计算/帮助功能,但(如果可能)不直接连接到类/构造函数。
链接
类的额外好处:使必要的url部分的计算变得懒惰(第一次需要时计算),但要记住(保存懒惰的计算结果/一次计算)。@PeterSeliger这就是我试图做的,但正如我所说,我在这方面很新。一旦解析和检索了urlPath和uuid,就不需要再对它们进行处理,但仍然不确定如何初始化这些属性。有了landet这种方法,并且已经考虑到了重构,出于兴趣,您可能还会阅读。。。。