Jquery推迟并承诺

我是jquery延迟和承诺的新手。 我想这样做

var maxRes=function() { var deferred=$.Deferred(); $("").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}没有方法’完成’

somebosy可以帮忙吗?

Deferred.promise()是一个方法,你需要调用它并返回从.promise()返回的值

所以

  return deferred.promise(); 

同样,不要使用闭包/全局对象将值从异步方法传递给回调。 您可以将值传递给完成的回调,如

 var newurl = '//placehold.it/256'; var maxRes = function () { var deferred = $.Deferred(); $("").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); }); 

演示: 小提琴