Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Refactor non-standard library callback into promise

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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

  });

}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!