babbaggeii
babbaggeii

Reputation: 7737

how to force async function to wait until finished

I've seen some similar questions here but none of them seem to be directly related to this. I'm reading a twitter stream and using socket.io to emit it as follows:

stream.on('data', function (data) {
            var geo=false,latitude,longitude;

      if(data.geo!=null){
          geo = true;
          latitude = data.geo.coordinates[0];
          longitude = data.geo.coordinates[1];

      }
      io.sockets.volatile.emit('tweets', {
          user: data.user.screen_name,
          text: data.text,
          geo : geo,
          latitude: latitude,
          longitude: longitude,
      });       
});

And I want to add some data processing before it gets emitted to the sockets. The code for the processing is:

var sentiment;
sentiment(data.text, function (err, result) {
    sentiment = result.score;
});

And I want to emit it as:

io.sockets.volatile.emit('tweets', {
              user: data.user.screen_name,
              text: data.text,
              geo : geo,
              latitude: latitude,
              longitude: longitude,
                  sentiment: sentiment
          }); 

But I get errors that I think are related to the async nature of the processing. How can I enforce it to wait for the processing function to be finished before emitting?

Upvotes: 0

Views: 295

Answers (1)

robertklep
robertklep

Reputation: 203231

You're overwriting your sentiment function:

var sentiment;                                <-- declare a var...
sentiment(data.text, function (err, result) { <-- ..and call it (which fails)
    sentiment = result.score; 
});

Upvotes: 2

Related Questions