I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :
/// Twitter.js
module.exports = Twitter
function Twitter(twitter) {
this.twitter = twitter
}
Twitter.prototype.friends = function(params) {
this.twitter.get('friends/list', params, (err, data) => {
if (err)
console.log(err)
console.log(data) // this prints data to the console but
// I want to export and save in a data structure
// array or object
}
}
///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')
var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})
If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array . Any help is and will be appreciated.
Looks like it might be an async problem. I'm not familiar with the Twitter API, but you could try (or a variation of) the following:
Twitter.prototype.friends = function(params, cb) {
this.twitter.get('friends/list', params, cb);
};
And then:
var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}, (err, data) => {
// Do something with the data here.
console.log('data', data);
});
It's the same logic, but moving the async response to a place more useful to what you might be trying to do.
I suggest using Promises to allow the calling code to work with the returned data:
Twitter.prototype.friends = function(params) {
return new Promise((resolve, reject) => {
this.twitter.get('friends/list', params, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
...
var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}).then((data) => {
// do something with data
console.log(data);
}).catch((err) => {
console.error(err);
});
The third parameter you are passing into the get
function is a callback
. If you add value to an array inside the callback and try to access it before the callback is invoked, that array will be empty/undefined.
The way I see it, you have two options:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.