I'm starting to learn node.js, and to aggregate multiple rss feeds in a single one, I'm fectching the feeds and then recreate a unique feed from the data I fecthed.
So, in order to handle multiple http requests asynchronously I use https://github.com/caolan/async#forEach which does the job.
But I can't figure how to return a value (the rss xml feed in my case).
Here is my code :
function aggregate(topic) {
async.forEach(topic.feeds,
function(item, callback) {
parseAndProcessFeed(item, callback);
},
function(err) {
// sort items by date
items.sort(function(a, b) {
return (Date.parse(b.date) - Date.parse(a.name));
});
var rssFeed = createAggregatedFeed();
console.log(rssFeed);
return rssFeed;
}
);
}
with console.log(rssFeed)
I can see the rss feed, so I think I'm missing something obvious.
How can I return the rssFeed
value?
Some help to get me back on seat would be great, thanks!
Xavier
forEach executes the callback function once for each array element. It always returns undefined.
Execute sequentially Using forEach , the records are saved in an undetermined order, but using for..of , they are saved sequentially. So in short: foreach doesn't handle callbacks in asynchronous way, therefore no waiting.
forEach is not designed for asynchronous code. (It was not suitable for promises, and it is not suitable for async-await.) For example, the following forEach loop might not do what it appears to do: const players = await this.
The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
You can't return value from asyncronious function. You need pass it into callback function. Like this:
function aggregate(topic, callback) {
async.forEach(topic.feeds,
function(item, callback) {
parseAndProcessFeed(item, callback);
},
function(err) {
// sort items by date
items.sort(function(a, b) {
return (Date.parse(b.date) - Date.parse(a.name));
});
var rssFeed = createAggregatedFeed();
callback(err, rssFeed);
}
);
}
aggregate(someTopic, function(err, result) {
// here is result of aggregate
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With