0

I have a function here that checks if a picture has the dimensions of 100 by 100 pixels and if so returns true

function checkDims(url) {
    var valid = $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            return true;
        }
        else {
            return false;
        }
    });
    return valid;
}

I want to set a variable called valid that checks by using a .load function to get the image size of a remote URL and I want it to return true or false accordingly. I know I'm setting it to a jQuery object but I want to get the results from the inner function.

I tried doing:

function checkDims(url) {
    var valid;
    $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            valid = true;
        }
        else {
            valid = false;
        }
    });
    return valid;
}

But it gave me undefined as a value for valid when I called the checkDims function

so if I called

var s = checkDims(a_url)

. It would return

undefined

7
  • 1
    load is an asynchronous call, you can not return from an asynchronous call. By the time the true or false is set, the function has already exited. Commented Jun 9, 2015 at 16:15
  • How would I workaround this. If possible? Do I need a setInterval function to wait? Commented Jun 9, 2015 at 16:16
  • 1
    You need to change your logic so that the callback fires off the next step of your process. Commented Jun 9, 2015 at 16:17
  • @epascarello Then why if I put a console.log within the call it will print? Commented Jun 9, 2015 at 16:22
  • Put it In what call? The load method? Because it that gets fired after the return. Commented Jun 9, 2015 at 16:23

1 Answer 1

1

You need to break up your logic into two steps since this is an asynchronous call.

function checkDims(url, callback) {
    $("<img/>").attr("src", url).load(function() {
        callback (this.width == 100 && this.height == 100);   
    }).on("error") { callback(false); });
}

function nextStep(isValid) {
    alert("The image is " + ((isValid) ? "" : "not ") + "valid"
}

checkDims("foo.gif", nextStep);
Sign up to request clarification or add additional context in comments.

3 Comments

So the nextStep function should return true or false? if I want to set var result = checkDims("foo.gif",nextStep)?
You can not return from this! It is impossible to return from an asynchronous call. You need to break your logic up so what ever you were doing after the call to checkDims needs to be in the function nextStep.
So there is no way to set checkDims to the result of nextStep callback?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.