Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value in a async.forEach in node js?

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

like image 316
xavier.seignard Avatar asked Oct 29 '12 22:10

xavier.seignard


People also ask

Can we return value in forEach?

forEach executes the callback function once for each array element. It always returns undefined.

Can I use async inside forEach?

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.

Is forEach async node JS?

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.

What is the return type of async await in node JS?

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.


1 Answers

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
});
like image 52
Vadim Baryshev Avatar answered Sep 18 '22 15:09

Vadim Baryshev