Reputation: 1349
I'm trying to understand how promises work, and apparently missing something.
In node I have a search function that uses the Twit module to return Twitter results, then I want to do something with the result:
var twitter = require('../server/twit');
exports.getTwitSearchResult = function(query, cb) {
var t = twitter.searchTwitter(query)
// do something with variable 't'
// var tweet = t.data.statuses
// ...
// ...
cb(null, tweet);
};
twitter function at '../server/twit'
:
var Twit = require('twit')
var bot = new Twit(config);
exports.searchTwitter = function(query){
var tsearch = function(query, callback){
return bot.get('search/tweets', {
q: query
, since: '2016-02-01'
, result_type: 'popular'
, count: 1
}, function(err, data, response){
callback(data)
});
};
tsearch(query, function(callback){
return callback
})
};
The problem is that 't' always returns as undefined
or [object Promise]
. I have tried several different ways of writing the functions using promises and callbacks, along the lines of something like this:
var twitter = require('../server/twit');
exports.getTwitSearchResult = function(query, cb) {
var t = function(query, callback){
return twitter.searchTwitter(query)
.then(function(tweet){
callback(tweet)
})
}
// do something with variable 't'
// var tweet = t.data.statuses
// ...
// ...
cb(null, tweet);
};
But then I get TypeError: Cannot read property 'then' of undefined
How can I write this better so that I can use the results returned from the Twit promise?
Upvotes: 1
Views: 1306
Reputation: 4662
Your variable t will always be undefined as the function is asynchronous and doesn't return anything. You need to use a callback instead.
For your '../server/twit' file:
var Twit = require('twit')
var bot = new Twit(config);
exports.searchTwitter = function(query, callback){
bot.get('search/tweets', {
q: query
, since: '2016-02-01'
, result_type: 'popular'
, count: 1
}, callback);
};
The main file:
var twitter = require('../server/twit');
exports.getTwitSearchResult = function(query, cb) {
twitter.searchTwitter(query, function(err, data, response) {
// do something with variable 'data'
// var tweet = data.statuses
// ...
// ...
cb(null, tweet);
});
};
If you want to use promises, you should switch to use the module twit-promise
and change your code to this:
var Twit = require('twit-promise')
var bot = new Twit(config)
exports.searchTwitter = function(query){
return bot.get('search/tweets', {
q: query
, since: '2016-02-01'
, result_type: 'popular'
, count: 1
});
};
var twitter = require('../server/twit');
exports.getTwitSearchResult = function(query, cb) {
twitter.searchTwitter(query)
.then(function(result) {
// do something with variable 'result'
// var tweet = result.data.statuses
// ...
// ...
cb(null, tweet);
})
.catch(function(err) {
cb(err);
});
};
Upvotes: 1