【发布时间】:2021-06-24 05:53:39
【问题描述】:
我正在制作一个“图像”构造函数。它从参数中保存元数据,并获取图像(基于元数据)。
function Image(filename) {
this.filename = filename;
fetch(`https://example.com/${this.filename}`)
.then( response => response.blob())
.then( blob => {
this.objectURL = URL.createObjectURL(blob);
this.timestamp = Date.now();
})
}
但是,当使用new Image('image.jpg') 运行时,它会返回一个只有 filename 属性的对象,并且稍后会附加带有 timestamp 的 objectURL。
我想要的是构造函数在返回对象之前等待 objectURL 和 timestamp。
提前致谢!
另外,您可以看到demonstration 在控制台中运行它,其中 title 和 number 是参数,filename 是根据它们计算的并在实际链接中使用,dataURL、timestamp、pinned属性在then()内部设置。 p>
【问题讨论】:
-
你不能让 Javascript 以这种方式“等待”。我会在这里建议选项:Asynchronous operations in constructor.
标签: javascript asynchronous promise es6-promise