colecmc colecmc - 2 months ago 7
Javascript Question

Unable to get promise value with Twitter API

I'm experimenting with NodeJS and the twitter API. I need help with a promise. The function

requestFollowers
should return a promise and it does. When I run the file in the node cli it says processing and never logs the value. How do I get the value I expect from it or how do I resolve it?

Here is what I have so for.



function requestFollowers(tweep) {
return new Promise(function(resolve, reject) {
twitter.get('followers/list', {
count: 200,
skip_status: true,
screen_name: tweep
}, function(error, followers) {
if (error) {
console.log('followers list/ error >', error);
reject(error);
} else {
resolve(followers.users.map(thing => thing.screen_name));
}
});
});
}

function onMention(error, tweets) {
if (error) {
console.log('mentions_timeline/ error >', error);
} else {
//console.log('mentions_timeline/ tweets >', tweets);
let mentioned = tweets[0].entities.user_mentions
.filter(thing => thing.screen_name !== user.screen_name)
.map(thing => thing.screen_name);

var list1 = requestFollowers(mentioned[0]),
list2 = requestFollowers(tweets[0].user.screen_name);

console.log('list1 >', list1.then(val => val).catch(error => error));
console.log('list2 >', list2.then(val => val).catch(error => error));
}
}

var config = require('./config'),
Twitter = require('twitter'),
twitter = new Twitter(config),
user = {
screen_name: 'screen_name'
},
/** @param {string} status */
getStatus = status => ({
status
});


twitter.get('statuses/mentions_timeline', user, onMention);




Answer

You can change this line console.log('list1 >', list1.then(val => val).catch(error => error)); to something like

list1.then(console.log).catch(console.error);

What you had is passing an unresolved promise chain to log and log doesn't resolve promises for arguments before printing them -- its synchronous. Also your then(val => val) is redundant even if that would work somehow -- you don't need another function that just returns its input.