1

I have a boolean function here called checkURL that checks if a picture has 100 x 100 pixels. If so it returns true. There is an asynchronous call within the function to check the size of the image.

function checkURL(url, callback) {

    var valid;
    var img = new Image();
    img.src = url;

    img.onload = function (callback) {

        valid = callback(img.width, img.height);

    };
    console.log(valid);
    return valid;
}


function nextStep(w, h) {
    if (w == 100 && h == 100) {
        return true;
    } else {
        return false;
    }
}

var pic_valid = checkURL(a_url, nextStep);

I am getting the error:

callback is not defined

within the checkURL function. I am also worrying that the variable valid within checkURL will end up being invalid.

ADDITIONAL EDIT: If I add console.log(valid); before returning valid I get undefined. Is this expected?

Jebathon
  • 4,310
  • 14
  • 57
  • 108
  • All the code that relies on the response needs to be in (or at least originated from) the callback. That's why there's a callback in the first place. – Lye Fish Jun 10 '15 at 15:15
  • Your error message doesn't make sense. What browser are you using? I'd expect it to say something like *"callback is not a function"* –  Jun 10 '15 at 15:20

2 Answers2

1

You define callback here:

function checkURL(url, callback) {

Then you redefine it here:

img.onload = function(callback){

… which masks the variable you actually give a value to.

Don't mask it:

img.onload = function(){
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Just change this line:

 img.onload = function(callback){

to this:

 img.onload = function(){

Because you are creating a new var callback in the new scope, and you don't need it there.

Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72