-->

jQuery的推迟和承诺(Jquery deferred and promises)

2019-10-19 13:02发布

我是新来的jQuery推迟和承诺。 我试图做到这一点

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);
                                       });

我不断收到此错误:遗漏的类型错误:对象函数(){返回null =一个n.extend(A,d):!?d}有没有方法 '完成'

可以somebosy请帮助?

Answer 1:

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

所以

 return deferred.promise();

同样不使用封闭/全局对象从异步方法回调值传递。 您可以将值传递给回调做类似

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 deferred and promises