Skip to content
Milind Soorya
Go back

How to return value from image.onload function

how-to-properly-return-your-data-from-image-onload-function

The Problem

When we are doing some operations on images in JavaScript we need to wait for the image to load before doing anything, like the code below

function parentFunction(URL) {
  var image = new Image();
  image.src = URL;
  image.onload = function () {
    // Do something
  };
}

Well the problem is how do I return something from the inner function? Don’t worry I spent half a day figuring it out for you πŸ˜….

The Solution

πŸ”– Use JavaScript promise. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value, need to learn more visit here. You can convert the original function to like the code below.

function parentFunction(URL) {
  return new Promise(async (resolve, reject) => {
    if (!URL) {
      reject();
    }
    var image = new Image();
    image.onload = function () {
      // Do something
      resolve(your_result);
    };
    image.src = URL;
  });
}

Share this post on:

Previous Post
How to add Next.js 11 image component to your website
Next Post
Tips For Using Async/Await - Write Better JavaScript!