jQuery延迟并承诺 [英] Jquery deferred and promises
本文介绍了jQuery延迟并承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是jquery延迟和承诺的新手.我正在尝试这样做
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);
});
我不断收到此错误: 未被捕获的TypeError:对象函数(a){return null!= a?n.extend(a,d):d}没有方法'done'
I keep getting this error: Uncaught TypeError: Object function (a){return null!=a?n.extend(a,d):d} has no method 'done'
有人可以帮忙吗?
推荐答案
Deferred.promise()是一种方法,您需要调用它并返回从.promise()
Deferred.promise() is a method, you need to invoke it and return the value returned from .promise()
所以
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);
});
演示:小提琴
这篇关于jQuery延迟并承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文