I am using twitter’s API to receive recent tweets by querying specific hash tags. The first GET request is to search/tweets
which takes the hashtag and others queries in it’s parameters. The response for this returns an array of tweets (objects). I push each of these id’s into an external array. Now I want to loop through this array and make another call to statuses/show
for each of these IDs so that I can get the location data of the user posting the tweet. The statuses/show
end-point only takes a single tweet id but I have an array. How would I go about using the same getRequest
function for an array of IDs?
I tried to implement it by reading online about Promises but it’s not working.
Here’s my code:
function getRequest(url, params) {
return new Promise(function (success, failure) {
twitterSearch.get(url, params, function (error, body, response) {
if (!error) {
success(body);
} else {
failure(error);
}
});
});
}
app.post('/twitter', (req, res) => {
console.log("body", req.body);
var tweetIDs = [];
var bounds = [];
getRequest('search/tweets', {q: req.body.tag, result_type:'recent', count:'100'})
.then((tweets) => {
tweets.statuses.map((status) => {
if(status.user.geo_enabled) {
console.log("ID: ", status.id);
tweetIDs.push(status.id);
}
});
return getRequest('statuses/show', tweetIDs); //I know tweetIDs is wrong, dont know what to do from here.
}).then((data) => {
console.log("User data for the ID")
console.log(data);
}).catch((error) => {
console.log(error)
});
res.send(bounds);
bounds.length = 0;
});
2
Answers
You nearly got it right! Map all tweets to Promises returned by your
getRequest()
function. Then, thePromise.all()
method will return you a single Promise that resolves when all of the promises in your array resolves.By the way, you can use
Array.reduce
instead ofmap
to both filter and map your array at the same time, this factor your code a little better.EDIT : Related jsfiddle
Replace the line
with