我以前从来没有创建过Javascript模块/库,所以这对我来说有点陌生,所以我为我缺乏对google的了解而道歉。
我正在创建一个库,它将保存来自用户提供的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 (以防止目标服务器进行速率限制)。
发布于 2020-10-05 08:15:47
经过大量的试验和错误,我最终做了更多这样的事情:
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,但现在,这是可行的。
https://stackoverflow.com/questions/64193119
复制相似问题