javascript - 如何让对象构造函数在返回之前等待承诺解决?
问题描述
我正在制作一个“图像”构造函数。它从参数中保存元数据,并获取图像(基于元数据)。
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')
,它会返回一个只有文件名属性的对象,并且稍后会附加带有时间戳的objectURL。我想要的是构造函数在返回对象之前等待objectURL和时间戳。
提前致谢!
此外,您可以看到在控制台中运行它的演示,其中title和number是参数,文件名由它们计算并在实际链接中使用,并且dataURL、timestamp、pinned属性在then()中设置。
解决方案
一个不错的模式是构建器,可能在上面的链接之一中引用,尽管我没有看到使用函数实例化的示例。直接在类上定义一个静态方法,作为构建需要异步操作的实例的工厂。
function Image({ filename, ...rest }) {
this.filename = filename;
this.dataUrl = rest.dataUrl;
this.timestamp = rest.timestamp;
}
Image.build = async function(filename) {
const fetchedData = await asyncFetchAndBlobHandling(filename);
return new Image({ filename, ...fetchedData })
}
const imgInstance = await Image.build(photo.jpg);
推荐阅读
- python - ValueError:只能将大小为 1 的数组转换为 Python 标量:将 lambda 应用于函数
- db2 - Cobol 调用存储过程 - SQLCODE -440
- reactjs - 在 Material UI appbar 中渲染图像
- python - 单选按钮的var值可以是Python中的字符串吗
- javascript - OpenLayers VectorLayers 从地图元素倾斜
- c++ - C中的通用头文件
- swift - 错误 ITMS-90046:“无效的代码签名权利”
- javascript - 可点击 tr 内的 href / router-link
- javascript - 仅针对使用 cookie 的不同用户的视图计数器递增
- sql - 如何更新冲突 postgres