mlnewbie mlnewbie - 2 months ago 13
Node.js Question

Using return value in another file in Node.js synchronously

I'm concatenating tweets from a defined user through a helper file and trying to retrieve it in my server.js but there the str value is still undefined (and this line gets executed first), then the console.log from my helper prints with the right value.

Output:


GET /login/twitter/callback 302 618.242 ms - 0

Concatenated Tweets in Server: undefined

Concatenated Tweets in Helper: Test Tweet 3 #TestTweet Test Tweet 2
Test Tweet 1


Can anyone help on what control flow I should use to call twitterHelper.getTweets functions to get the returned str in the server please? Thanks!

Server.js

app.get('/login/twitter/callback',
passport.authenticate('twitter', {failureRedirect: "/login"},
function(req, res) {
// auth success
async.waterfall ([
function(callback) {
callback(null, twitterHelper.getTweets(user));
},
function(str, callback) {
console.log("Concatenated Tweets in Server: " + str);
callback(null);
}
],
function(err) {
if(err)
console.log("Error: " + err);
}
);
}
)
);


Helper.js

var concatTweets = '';
var promise = new Promise(
function(resolve, reject) {
T.get('statuses/user_timeline', params, function( err, data, response) {
if(err)
reject(err);
else {
for (var i = 0; i < data.length ; i++)
concatTweets = concatTweets + " " + data[i].text;
resolve(concatTweets);
}
})
}
).then(
str => {
console.log("Concatenated Tweets in Helper: " + str);
return str;
}, err => {
console.log(err);
return err;
}
);

Answer Source

Instead of using this longway you can use this simple way by promise.

Helper.js

var concatTweets = '';
var getTweets = function(user){
    var promise = new Promise(function(resolve, reject) {
        T.get('statuses/user_timeline', params, function( err, data, response) {
            if(err){
                reject(err);    
            } else {
                for (var i = 0; i < data.length ; i++) 
                    concatTweets = concatTweets + " " + data[i].text; 
                console.log("Concatenated Tweets in Helper: " + concatTweets);
                resolve(concatTweets);  
            }
        })
    });
    return promise; 
}

Server.js

app.get('/login/twitter/callback', passport.authenticate('twitter', {failureRedirect: "/login"},function(req, res) { 
    // auth success 
    twitterHelper.getTweets(user).then(str=>{
        console.log("Concatenated Tweets in Server: " + str);
    }).catch(err=>{
        console.log("Error: " + err);
    });
}));

I hope this will work for you.