-1

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".

Mike Irving
  • 1,480
  • 1
  • 12
  • 20
Mr. lindroid
  • 162
  • 1
  • 12
  • What HTTP Status Code is being returned for your not found images? If an error page is coming back as 200, then JavaScript may still think it has been successful – Mike Irving Mar 20 '22 at 16:03

1 Answers1

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 })
Musa
  • 96,336
  • 17
  • 118
  • 137