【问题标题】:How to use jQuery's promises so that functions are not nested如何使用 jQuery 的 Promise 使函数不嵌套
【发布时间】:2013-04-08 05:34:10
【问题描述】:

我想我增加了一层复杂性。这是我得到的:

;(function($, window, undefined) {
    function download() {
        var local = {};
        local.data = {};
        local.data.method = 'getMyData';
        local.dataType = 'json';
        local.Promise = $.ajax('myComponent.cfc', local);
        local.Promise.done(PromiseDone);
        local.Promise.fail(PromiseFail);
    }

    function PromiseDone(result) {};
    function PromiseFail(myEvent) {};
})(jQuery, window);

我想做的是这样的:

;(function($, window, undefined) {
    var Variables = {};
    Variables.Promise = $.Deferred();

    function download() {
        var local = {};
        local.data = {};
        local.data.method = 'getMyData';
        local.dataType = 'json';
        Variables.Promise = $.ajax('myComponent.cfc', local);
    }

    Variables.Promise.done(function(result) {
    });
    Variables.Promise.fail(function(myEvent) {
    });
})(jQuery, window);

我的目标是扁平化 JavaScript,这样我的函数就不会嵌套。

问:我的想法是否可行,或者deferred 是否需要resolve 才能被视为done

【问题讨论】:

    标签: javascript jquery promise


    【解决方案1】:

    您确实增加了不必要的复杂性。 $.ajax 已经返回了一个承诺,所以没有理由再创建一个:

    ;(function($, window, undefined) {
        function download() {
            return $.ajax({
               data    : {method:'getMyData'},
               dataType: 'json'
            });
         }
    
        var ajaxCall = download();
    
        ajaxCall.done(function(result) {
              // do something with result
        });
    
        ajaxCall.fail(function() {
             // failed
        });
    })(jQuery, window);
    

    【讨论】:

    • 天啊。返回 $.ajax()。太棒了!
    • @Phillip - 稍微改变了答案!
    猜你喜欢
    • 2020-10-19
    • 2019-03-29
    • 1970-01-01
    • 2019-01-09
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    相关资源
    最近更新 更多