Reputation: 445
I am new to jquery deferred and promises. I am trying to do this
var maxRes=function()
{
var deferred=$.Deferred();
$("<img/>").attr("src", newurl).load(function(){
s = {w:this.width, h:this.height};
imgHeight = this.height ;
deferred.resolve();
});
return deferred.promise;
}
maxRes().done(function(){
if(imgHeight >=720)
{
temp="...[HD]"
}
else
{
temp = "...";
}
console.log(temp);
});
I keep getting this error: Uncaught TypeError: Object function (a){return null!=a?n.extend(a,d):d} has no method 'done'
Can somebosy please help?
Upvotes: 1
Views: 1428
Reputation: 388316
Deferred.promise() is a method, you need to invoke it and return the value returned from .promise()
So
return deferred.promise();
Again don't use closure/global objects to pass values from the async method to the callback. You can pass values to the done callback like
var newurl = '//placehold.it/256';
var maxRes = function () {
var deferred = $.Deferred();
$("<img/>").attr("src", newurl).load(function () {
var s = {
w: this.width,
h: this.height
};
//pass the dimensions are arguments to the done callback
deferred.resolve(s);
});
return deferred.promise();
}
maxRes().done(function (s) {
//recieve the dimension as a parameter and use it instead of the shared variable
//declare temp as a local variable instead of messing up the global scope
var temp;
console.log(s)
if (s.height >= 720) {
temp = "...[HD]"
} else {
temp = "...";
}
console.log(temp);
});
Demo: Fiddle
Upvotes: 2