【问题标题】:Jquery deferred and promisesJquery 延迟和承诺
【发布时间】:2014-03-11 04:37:19
【问题描述】:

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

我不断收到此错误: Uncaught TypeError: Object function (a){return null!=a?n.extend(a,d):d} has no method 'done'

有人能帮忙吗?

【问题讨论】:

    标签: jquery promise jquery-deferred


    【解决方案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);
    });
    

    演示:Fiddle

    【讨论】:

    • @PratikJoshi 是的,他是 :)
    • 当您可以简单地使用deferred.resolve(this) 时,为什么要将图像的属性重新捆绑为s?这个和其他简化here
    • @Beetroot-Beetroot 这只是一个关于应该如何完成的演示......然后为了争论,如果我们想传递一些自定义处理的属性?
    猜你喜欢
    • 1970-01-01
    • 2015-03-27
    • 2023-03-21
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2015-08-25
    • 2011-07-23
    相关资源
    最近更新 更多