1

I'm working on rewriting a userscript that I wrote a week or so ago, but I stumbled upon a problem. I am by no means an expert on JavaScript, and I'm not sure what I'm doing wrong with my code.

Here is my code:

function checkImageValidity(url) {
    return imageExists(url, function(exists) {
        return exists;
    });
}

function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}

Inside my call to imageExists, I've tried adding console.log(url + " -- " + exists), which is giving me the results I expected from my testing URLs.

The problem is, this is not returning properly to checkImageValidity, it's always being returned as "undefined".

What am I doing wrong?

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • Two things: 1. There is nothing in `checkImageValidity` that returns either `true` or `false`. It doesn't have any return value at all (so calling it will yield `undefined`). The callback you're passing `imageExists` returns a value, but nothing uses it. 2. It's impossible for either of them to *return* the result. It's not available as of when they return. See the linked question's answers for details. – T.J. Crowder Feb 23 '18 at 15:03
  • You cannot return anything from the inner callback to `checkImageValidity()` as the callback is asynchronous. This means it will execute a long time (in processing terms) after execution of `checkImageValidity()` has ended. You need to refactor your code so that all logic dependant on the callback is executed *within* the callback – Rory McCrossan Feb 23 '18 at 15:04
  • @T.J.Crowder I'm having a really hard time wrapping my mind around the answers on that page and how to fix the issue I am having. Thanks for pointing me in the right direction though – GrumpyCrouton Feb 23 '18 at 15:39
  • @GrumpyCrouton: Just like `imageExists`, `checkImageValidity` will need to accept a callback it calls with the result. It cannot *return* the result, because it returns before the result is known. (Or instead of raw callbacks, you could uses promises, which have some advantages over simple callbacks but are slightly more complicated.) – T.J. Crowder Feb 23 '18 at 15:48

0 Answers0