1

我无法获得 $.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
    });
}
4

3 回答 3

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
});
于 2013-07-07T20:25:51.107 回答
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
    });
}

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

于 2013-07-07T20:01:14.033 回答
0

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

例如类似的东西

    // 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
    });
于 2015-05-08T16:28:42.623 回答