I'm using the twit library for nodejs which have async calls, and I made functions like this:
function getUserFromSearch(phrase) {
T.get('search/tweets', { q: phrase+' lang:pt', count: 1 }, function(err, data, response) {
data['statuses'].forEach(function(element) {
var result = "maybe";
say('getting user profile from search for '+phrase, result);
console.log(element);
return element['user']['screen_name'];
}, this);
})
}
Since T.get() is executed asynchonously, whenever I do
var username = getUserFromSearch('banana');
I get username=undefined
because it takes time to return things. The obvious solution would be to implement a callback like this:
function getUserFromSearch(phrase, callback) {
T.get('search/tweets', { q: phrase+' lang:pt', count: 1 }, function(err, data, response) {
data['statuses'].forEach(function(element) {
var result = "maybe";
say('getting user profile from search for '+phrase, result);
console.log(element);
callback(element['user']['screen_name']);
}, this);
})
}
But I don't think this is the best solution, because I need to create a callback function just for this. Isn't there a way to pass the username 'pointer' like this: getUserFromSearch('banana', username);
in such a way that the function alters the value of username? Is there even a better way?