首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在对象实例化时,如何最好地处理其属性之一的异步初始化?

在对象实例化时,如何最好地处理其属性之一的异步初始化?
EN

Stack Overflow用户
提问于 2020-10-04 17:43:35
回答 1查看 71关注 0票数 1

我以前从来没有创建过Javascript模块/库,所以这对我来说有点陌生,所以我为我缺乏对google的了解而道歉。

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

这是基本的,但这是我到目前为止所知道的:

代码语言:javascript
复制
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
  }
}

理想情况下,我会让模块在构造时自动获取所有信息:

代码语言:javascript
复制
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 (以防止目标服务器进行速率限制)。

EN

回答 1

Stack Overflow用户

发布于 2020-10-05 08:15:47

经过大量的试验和错误,我最终做了更多这样的事情:

代码语言:javascript
复制
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函数发送一个promise,但现在,这是可行的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64193119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档