'JavaScript "Image.onload" fires even if the image is not found [duplicate]

I am trying to load some image for a HTML canvas game. And I want them to load before I start the game. So I created a function to load them synchronously before my game starts. But the problem is,
if the image does not exists, it still fires "Image.onload()".
I want to return an object with "error=true" if the image doesn't exist. But couldn't find a way.

Here is the function I wrote:

function loadImages(images) {
    return {
        list: images,
        loaded: {},
        failed: {},
        _load(src, name){
            return new Promise((resolve)=>{
                let image = new Image()
                image.onload = resolve({ name, src, image, error: false })
                image.onerror = resolve({ name, src, image: null, error: true })
                image.src = src
            })
        }
    }
}

let myLoader = loadImages("some image list")
let image = await myLoader._load("https://someUrl.com/img.png", "imageName")

console.log(image)

if you look at the console you'll see the "onload" gets fired not "onerror".



Solution 1:[1]

onload and onerror should be set to a function, instead you're calling a function and assigning the return to them.

image.onload = e => resolve({ name, src, image, error: false })
image.onerror = e => resolve({ name, src, image: null, error: true })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Musa