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?
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(){
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.