-1

I am using the fabricjs package and want to make use of the fabric.Image.fromURL function. The documentation for this function is below:

(static) fromURL(url, callbackopt, imgOptionsopt)

Creates an instance of fabric.Image from an URL string
Parameters:

Name Type Attributes Description
url String URL to create an image from
callback function <optional> Callback to invoke when image is created (newly created image is passed as a first argument). Second argument is a boolean indicating if an error occurred or not.
imgOptions Object <optional> Options object

I would to refactor my code to use modern Promise notation instead of nesting callbacks. Can I refactor this function into a Promise?

Currently if I want to add two images in a row, my code looks like this:

  # add first image
  fabric.Image.fromURL(url1, function (oImg: any) {
    canvas.add(oImg);
    # add second image
    fabric.Image.fromURL(url2, function (oImg: any) {
      canvas.add(oImg);
    }  
  })

I would love to be able to rewrite it as

async def addImages() {
    await promisifiedImageFromURL(url1)
    await promisifiedImageFromURL(url2)
}

I have looked into util.promisify (https://nodejs.org/api/util.html#utilpromisifyoriginal) but this function expects the corresponding function to be in a specific format: a single error-first callback. The fromURL function, on the other hand, is in a nonstandard format, which is where I am having trouble

I'm looking into custom promisified functions, but I'm honestly in over my head here

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
C_Z_
  • 7,427
  • 5
  • 44
  • 81
  • `util.promisify` does not expect two callbacks, it expects a single error-first callback. The example with separate onError and onSuccess callbacks is showing a [custom promisified function](https://nodejs.org/api/util.html#custom-promisified-functions), creating a `new Promise` and interfacing appropriately with the non-standard function, which is what you should be doing here. – jonrsharpe Jul 18 '22 at 20:43

1 Answers1

1
const promiseFromUrl = (url, imgOptions) => {

  return new Promise((res, rej) => {

    const callback = (image, isError) => {
      if (isError) rej(new Error('Some error occurred'));
      else res(image);
    };
    fromURL(url, callback, imageOptions);

  });

}
Evert
  • 93,428
  • 18
  • 118
  • 189