Check if src image is valid

I’m trying to check if an image url is valid before setting in my img src. At the moment this is what I have:

function checkURL(url) {
    var img = new Image();
    
    img.onerror = function () {
        return false;
    }

    img.onload = function () {
        return true;
    }

    img.src = url;
}

In both cases is returning undefined instead of true/false.

What can I do to solve my issue? I’m using jQuery 3.6.0.