【问题标题】:Change data result while passing promise up chain?向上链传递承诺时更改数据结果?
【发布时间】:2013-02-25 22:18:11
【问题描述】:

我正在尝试通过 jQuery 迁移到使用 Promise。在我的原始代码中,我有一个回调参数,用于接收修改后的数据:

var getRss = function (url, fnLoad) {
    $.get(url, function (data) {
        var items = [];
        $(data).find('item').each(function (index) {
            items.push({
                title: $(this).find('title').text(),
                pubDate: $(this).find('pubDate').text()
            });
        });

        fnLoad(items);
    });
}

我尝试更改为承诺,但“完成”返回未修改的数据而不是解析的数据:

var getRss = function (url) {
    return $.get(url).done(function (data) {
        var items = [];
        $(data).find('item').each(function (index) {
            items.push({
                title: $(this).find('title').text(),
                pubDate: $(this).find('pubDate').text()
            });
        });
    });
}

然后像下面这样使用它,但我得到的是原始 XML 版本,而不是转换为对象的修改版本:

 getRss('/myurl').done(function (data) {
      $('body').append(template('#template', data));
  });

【问题讨论】:

  • 您在第二个 sn-p 中不接受 fnLoad 参数。
  • 谢谢我修正了错字。在第二个 sn-p 中,我期望取回之前“完成”执行的修改数据,但它始终在整个链中返回原始数据。

标签: javascript jquery jquery-deferred promise


【解决方案1】:

您想使用then(阅读pipe 的文档,请参阅pipe() and then() documentation vs reality in jQuery 1.8):

function getRss(url) {
    return $.get(url).then(function (data) {
        var items = [];
        $(data).find('item').each(function (index) {
            items.push({
                title: $(this).find('title').text(),
                pubDate: $(this).find('pubDate').text()
            });
        });
        return items;
    });
}

...它的工作原理类似于

function getRss(url) {
    var dfrd = $.Deferred();
    $.get(url).done(function (data) {
        var items = [];
        $(data).find('item').each(function (index) {
            items.push({
                title: $(this).find('title').text(),
                pubDate: $(this).find('pubDate').text()
            });
        });
        dfrd.resolve(items);
    }).fail(dfrd.reject);
    return dfrd.promise();
}

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2018-03-18
    • 2017-11-28
    • 2017-04-18
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2016-12-05
    相关资源
    最近更新 更多