【问题标题】:chaining Jquery Deferred objects with promises用 Promise 链接 Jquery Deferred 对象
【发布时间】:2015-03-05 18:23:41
【问题描述】:
function addAccountData(data) {


var queryResults = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

var key;
var displayProps = decodeURIComponent(getQueryStringParameter("qProps")).split(",");
var keyIndex;
var resultIndexes = [];

for (var i = 0; i < queryResults[0].Cells.results.length; i++) {
    key = queryResults[0].Cells.results[i].Key;
    keyIndex = displayProps.indexOf(key);

    if (keyIndex > -1) {
        resultIndexes.push(i);
    }
}

    var promises = [];
    for (var h = 0; h < queryResults.length; h++) {
        var cellValues = [];

        for (var i = 0; i < resultIndexes.length; i++) {
            cellValues.push(queryResults[h].Cells.results[resultIndexes[i]].Value);
        }

       // getAccountInfo(cellValues);
        var deferred = $.Deferred();

        //add data from SharePoint Accounts list

            if (cellValues[4] != null) {
                $.when(getAccountInfo(cellValues)).done(function (data) {
                    tempResults.push(data);
                    deferred.resolve(tempResults);
                });
            }

        promises.push(deferred);
    }

 $.when.apply($,promises).done(function() {
     alert('yes');
     spinner.stop();
 }, 
  function(e) {
     console.log("My ajax failed");
 });
}

我的 jquery 代码中的这个函数使用延迟对象并承诺解析一个异步函数。定义了一组承诺,并使用.when.apply 传递了该数组。但是,在为每个 promise 调用 deferred.resolve 之后,它不会回调 $.when.apply($,promises).done(function() ... ) 中的语句,从未调用过。有人能指出我正确的方向吗?

【问题讨论】:

  • 如果不查看更多信息(包括 getAccountInfo() 函数),很难判断。此外,没有理由人为地创建您的 $.Deferred() 对象以存储到您的数组中——只需添加 getAccountInfo() 的结果,因为这似乎已经返回了一个承诺。

标签: jquery


【解决方案1】:

我只能怀疑getAccountInfo() 已经返回了一个承诺(很可能是一个 jQuery XHR 对象)。

这意味着您不需要自己的延迟基础设施,您可以直接使用 jqXhr 对象。

为了好玩,我已经重写了你的代码,没有任何显式循环。

function addAccountData(data) {
    var table = data.d.query.PrimaryQueryResult.RelevantResults.Table;
    var displayProps = decodeURIComponent(getQueryStringParameter("qProps")).split(",");
    var requests = table.Rows.results.map(function (row) {
        // find Cells whose .Key is in displayProps and get their .Value
        return row.Cells.results.filter(function (cell) {
            return displayProps.indexOf(cell.Key) > -1;
        }).map(function (cell) {
            return cell.Value;
        });
    }).filter(function (cellValues) {
        return cellValues[4] !== null;
    }).map(getAccountInfo);

    $.when.apply($, requests).always(function () {
        spinner.stop();
    }).fail(function(e) {
        console.log("Ajax failed");
    });
}

这会将您的 Rows 从 queryResults 映射到 Cell 值数组,并将 它们 映射到 getAccountInfo()(我假设它返回单个 jqXhr 对象)。

它非常有效地将您的行映射到由$.when 处理的Ajax 请求承诺。您可能希望您的微调器停止始终,而不仅仅是整体成功。

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多