我是jquery deferred和promises的新手。我正在努力做到这一点
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);
});
我一直收到这个错误: 未捕获的TypeError:对象函数(a){return null!= a?n.extend(a,d):d}没有方法'done'
请帮忙吗?
答案 0 :(得分:2)
Deferred.promise()是一个方法,您需要调用它并返回从.promise()
返回的值
所以
return deferred.promise();
再次不要使用closure / global对象将值从异步方法传递给回调。您可以将值传递给完成的回调,如
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);
});
演示:Fiddle