0

I'm making an "Image" constructor function. It saves metadata from arguments, and fetches the image (based on metadata).

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

However, when ran with new Image('image.jpg'), it returns an object with only filename property, and objectURL with timestamp are appended later. What I want is constructor function to wait for objectURL and timestamp before returning an object.

Thanks in advance!

Additionally, you can see demonstration of running it in console, where title and number are arguments, filename is computed from them and used in real link, and dataURL, timestamp, pinned properties are set inside then().

  • You can't make Javascript "wait" in that way. I would suggest the options here: [Asynchronous operations in constructor](https://stackoverflow.com/questions/49905178/asynchronous-operations-in-constructor/49906064#49906064). – jfriend00 Mar 27 '21 at 15:59

1 Answers1

1

A nice pattern is the builder, likely referenced in one of the links above, although I did not see an example using functional instantiation. Define a static method directly on the class to act as a factory in building instances that require async operations.

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);
Greg Brodzik
  • 1,267
  • 4
  • 5