[英]Running a function after another function with loops & promises in jQuery/JavaScript
我正在一个大学/个人项目中,该项目需要RSS网址并通过一系列API发送它们。 代码如下:
var tempStory = [];
function getFeed () {
$.getJSON('spoonfed/app/scripts/categories.json', function(categories){
for (var category in categories){
if (categories[category][2] === true){
getFeedURLs(categories[category][0]).then(function(rssData) {
for (var item in rssData){
tempStory.push(rssData[item]);
}
});
}
}
});
}
除了每个类别中的10个新闻故事外,我还需要遍历多个类别,然后将这些新闻推送到tempStory数组中。 我需要在此数据数组上运行另一个函数。 我认为诺言是关键,但我无法理解在这种情况下如何使用诺言。
我们将不胜感激任何帮助,如果需要,我很乐意提供更多代码,包括category.json文件的结构和getFeedURLs函数。
如果问题是您只是想弄清楚如何获取所有数据,则可以执行以下操作:
function getFeed() {
return $.getJSON('spoonfed/app/scripts/categories.json').then(function (categories) {
var tempStory = [], promises = [];
for (var category in categories) {
if (categories[category][2] === true) {
promises.push(getFeedURLs(categories[category][0]).then(function (rssData) {
for (var item in rssData) {
tempStory.push(rssData[item]);
}
}));
}
}
return $.when.apply($, promises).then(function() {
// return results array as the fulfilled value of the promise
return tempStory;
});
});
}
getFeed().then(function(data) {
// all the data available here
}, function(err) {
// error here
});
关键方面是:
getFeed()
返回原始的ajax许诺。 $.when()
与您的promise数组一起使用以知道何时完成所有这些操作 $.getJSON.then()
处理程序,返回$.when()
承诺将链到$.getJSON()
的承诺,让你返回结果的数组。 $.when().then()
处理程序中,返回我们的结果,以便成为最终承诺的实现值 注意:由于您选择了累加tempStory
数组的方式,因此其结果并非有保证的顺序。 可以编写其他代码来维护顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.