$ .when.apply不评估数组中任何已定义的函数

时间:2013-07-07 19:51:24

标签: javascript jquery

我无法获得$ .when.apply来评估数组中任何已定义的函数,我在这里做错了什么?

function Logic(address) {
    this.address = address;
}

Logic.prototype.Get = function (pk, success, failure) {
    var scope = this;

    return $.ajax({
        url: scope.address + '/Get',
        type: "GET",
        data: { 'pk': pk },
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            success(data.hasOwnProperty("d") ? data.d : data);
        },
        failure: function (ex) {
            failure(ex);
        }
    });
};

function Screen(options) {
var scope = this;

if (options.pullings != null)
    {
        $.each(options.pullings , function (i, pulling)
        {
            scope.pullings.push(function () {

                return pulling.logic.Get($('[name="' + pulling.pkField + '"]').val(),
                function (row) {
                    $('#' + pulling.displayControlID).val(row[pulling.displayField]);
                }, null);
            });
        });
    }
}

Screen.prototype.Fill = function (pk) {
    var scope = this;

    $.when.apply($, scope.pullings).then(function () {
      // none of the functions ever gets called and just enters this block
    });
}

3 个答案:

答案 0 :(得分:1)

因为$.when()需要Promises或普通值。传入的函数对象被视为值。你为什么期望它们被自动调用?您必须手动执行此操作:

$.when.apply($, $.map(scope.pullings, function(fn) {
    // calls every function
    return fn();
})).then(function() {
    // this block gets called when all results are available
});

答案 1 :(得分:0)

看起来像语法错误,更改:

Screen.prototype.Fill = function (pk) {
    var scope = this;

    $.when.apply($, scope.pullings).then(function () {
      // none of the functions ever gets called and just enters this block
    }
}

为:

Screen.prototype.Fill = function (pk) {
    var scope = this;

    $.when.apply($, scope.pullings).then(function () {
      // none of the functions ever gets called and just enters this block
    });
}

这是我最初的想法,您是否检查过控制台以查看可能出现的错误?

答案 2 :(得分:0)

$.when.apply的一个被忽视的替代方法是在循环中积累when个承诺,例如使用模式promise = $.when(promise, anotherpromise)

e.g。

之类的东西
    // Start with a resolved promise - which undefined represents!
    var promise;
    $.each(options.pullings, function (i, pulling) {
        promise = $.when(promise, Get($('[name="' + pulling.pkField + '"]').val(),
               function (row) {
                    $('#' + pulling.displayControlID).val(row[pulling.displayField]);
               }, null);
    });

    promise.then(function(){
        // called when all promises are completed
    });