2

I am trying to migrate to using promises via jQuery. In my original code, I have a callback parameter that takes in modified data:

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);
    });
}

I tried changing to promise, but the "done" returns the unmodified data instead of the parsed one:

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()
            });
        });
    });
}

Then using it like below but I get the original XML version, not the modified one that was converted to an object:

 getRss('/myurl').done(function (data) {
      $('body').append(template('#template', data));
  });
TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • you're not accepting the `fnLoad` parameter in your second snippet. – jbabey Feb 25 '13 at 14:12
  • Thx I fixe the typo. In the 2nd snippet, I'm expecting to get back the modified data that the previous "done" performed, but it's always returning the original data throughout the chain. – TruMan1 Feb 25 '13 at 14:13

1 Answers1

7

You want to use then (read the docs for pipe, see 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;
    });
}

…which works like

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();
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375