Reputation: 36078
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));
});
Upvotes: 2
Views: 3176
Reputation: 664484
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();
}
Upvotes: 7