I am working with a call to the twitter API which allows me to use promises. I thought it looked cleaner if I would define my function that gets passed to .then() before hand (see below).
var T = new twit({
consumer_key: apikey,
consumer_secret: apisecret,
access_token: access,
access_token_secret: accesssecret
});
// error function
function errorFunc(err){
console.log(err);
}
// processing function
function thenFunc(result){
const tweets = result.data.statuses;
const cities = tweets.map(function (tweet) {
return tweet.user.location;
});
var out = [];
var outTweet = [];
// edit each city name and add to an array
for (var i = 0; i < tweets.length; i++) {
var city = cities[i];
var edit = city.split(',').join("+").replace(/\s/g, '');
if (edit.length > 0){
out.push(edit);
outTweet.push(tweets[i].text);
}
}
console.log(outTweet);
console.log(out);
}
T.get('search/tweets', { q: query, count: count_ }).catch(errorFunc()).then(thenFunc());
Here I get an error saying "TypeError: Cannot read property 'statuses' of undefined at thenFunc". But then when I define the same function directly within the .then() scope everything works (see below).
var T = new twit({
consumer_key: apikey,
consumer_secret: apisecret,
access_token: access,
access_token_secret: accesssecret
});
T.get('search/tweets', { q: 'trump', count: 1}).catch((function (err){
console.log('err');
})).then(function (result){
const tweets = result.data.statuses;
const cities = tweets.map(function (tweet) {
return tweet.user.location;
});
var out = [];
var outTweet = [];
// edit each city name and add to an array
for (var i = 0; i < tweets.length; i++) {
var city = cities[i];
var edit = city.split(',').join("+").replace(/\s/g, '');
if (edit.length > 0){
out.push(edit);
outTweet.push(tweets[i].text);
}
}
console.log(outTweet);
console.log(out);
console.log(tweets);
});
However, I find it easier to read if I separate the functions and define them before I pass them to the .then() as I did in the first section of code I posted. Is there a way I can still write my script this way so that it works, or am I forced to define the function within the .then() brackets? I understand that JS runs asychronously, and so the error comes from the 'results.data.statuses' being undefined at the time that the function is written, but I thought that because the function doesn't get called until the .then() call that this wouldn't matter.