首页 > 解决方案 > 如何让对象构造函数在返回之前等待承诺解决?

问题描述

我正在制作一个“图像”构造函数。它从参数中保存元数据,并获取图像(基于元数据)。

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时间戳。

提前致谢!

此外,您可以看到在控制台中运行它的演示,其中titlenumber是参数,文件名由它们计算并在实际链接中使用,并且dataURLtimestamppinned属性在then()中设置。

标签: javascriptasynchronouspromisees6-promise

解决方案


一个不错的模式是构建器,可能在上面的链接之一中引用,尽管我没有看到使用函数实例化的示例。直接在类上定义一个静态方法,作为构建需要异步操作的实例的工厂。

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);

推荐阅读