How to return value from image.onload function

Milind Soorya / June 16, 2021

1 min read

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

Learn about building products as a Data Scientist

Get a once-per-month email with my latest article and additional details about my launches, products, and experiments ✨

No spam, sales, or ads. Unsubscribe as your heart desires.