[英]Change data result while passing promise up chain?
I am trying to migrate to using promises via jQuery. 我正在尝试通过jQuery迁移到使用Promise。 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: 然后像下面这样使用它,但是我得到的是原始XML版本,而不是转换为对象的修改后的版本:
getRss('/myurl').done(function (data) {
$('body').append(template('#template', data));
});
You want to use then
(read the docs for pipe
, see pipe() and then() documentation vs reality in jQuery 1.8 ): 你想使用then
( 在jQuery 1.8中读取pipe
的文档,参见pipe()然后()文档与现实 ):
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.