how to return value from this async function? img.onLoad event

52 views Asked by At

How do I return height from function getImgSize(imgSrc)? Bear in mind that onload() is async.

function getImgSize(imgSrc) {
  const img = new Image();

  img.onload = function() {
    const height = img.height;
  }
  img.src = url;
}
1

There are 1 answers

0
mochaccino On

You can wrap it in a promise (called "promisification"):

function getImgSize(imgSrc){
  const img = new Image();

  img.src = imgSrc;

  return new Promise((resolve, reject) => {
    img.onload = function() {
      const height = img.height; 

      resolve(height); // Promise resolves to this value
    };

    img.onerror = function(error) {
      reject(error); // Promise rejects with the error
    };
  });
}

But then you can only call this function in an async context. Most modern browsers support top-level await (in scripts where type=module), but just in case, you may want to wrap it in a function:

(async () => {
  const heightOfImage = await getImgSize("...");
})();