Async Function Not Waiting for Edited Image to Load

I’m running into a JavaScript issue where an async function is supposed to load an image (edited in photo editing software like Meitu, Adobe Lightroom, Illustrator) and then apply additional processing, but it doesn’t seem to be waiting for the image to fully load before moving to the next step. Here’s the function:

async function loadImageAndProcess(url) {
    try {
        const response = await fetch(url);
        const blob = await response.blob();
        const img = new Image();
        img.src = URL.createObjectURL(blob);
        
        img.onload = () => {
            console.log("Image loaded:", img);
            // Further image processing here
        };
    } catch (error) {
        console.error("Error loading image:", error);
    }
}

The issue is that img.onload sometimes fires inconsistently, especially with large images edited in external software. I’ve tried adding more await calls, but it hasn’t resolved the issue. Has anyone else had issues with async image loading in JavaScript, especially for large, edited images?

What happens if you define the onload before you define the src? (Are you creating a race condition accidentally - if you tell it the src, and it finishes loading before the onload is defined, it wouldnt fire the onload because its already loaded?)

I hadn’t thought about it like that, but it totally makes sense if the src is set before onload, there’s definitely a chance it could load too fast and miss the onload event entirely.
thanks for the suggestion

Hi @dexterhale398, also you’re only catching fetch errors here… do you get some output if you also log image errors with e.g. img.onerror = console.error?

Might this be worth looking at?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.