How to sequentially handle asynchronous results fr

2019-09-06 10:33发布

问题:

This question might be a little vague, but I'll try my best to explain.

I'm trying to create an array of all of the tweets that I can retrieve from Twitter's API, but it limits each request to 200 returned tweets. How can I request to Twitter asynchronously up to the maximum limit of 3200 returned tweets? What do I mean is, is it possible to asynchronously call Twitter's API but build the array sequentially, making sure that the tweets are correctly sorted with regard to date?

So, I have an array:

var results = [];

and I'm using node's request module:

var request = require('request');

what I have right now (for just the limit of 200) is

request(options, function(err, response, body) {
    body = JSON.parse(body);
    for (var i = 0; i < body.length; i++) {
        results.push(body[i].text);
    }
    return res.json(results);
});

I've looked into maybe using the 'promise' module, but it was confusing to understand. I tried using a while loop, but it got complicated because I couldn't follow the path that the server was taking.

Let me know if this didn't explain things well.

In the end, I want results to be an array populated with all of the tweets that the requests send.

回答1:

I would suggest using request-promise instead of request. Here is my solution.

var rp = require('request-promise');
var tweets = [];
var promises = [];
for (var i =1; i< 10; i++){
     var promise = rp(options);
    promises.push(promise);
}
Promise.all(promises).then(function(data){
  data.forEach(function(item){
    // handle tweets here
  });
  return res.json(tweets);
});