Sahil Purav Sahil Purav - 6 months ago 49
Node.js Question

BlueBird Promises returns "Undefined" when return inside "then" function

Here is my Code:

Checking if user is folowing official Twitter Account (here I've returned new Promise

var isFollowing = function(sender) {
return new promise(function(resolve, reject) {
var following = false;
var params = {
source_id: sender,
target_screen_name: config.get('twitter.official_account')
};
TwitObj.get('friendships/show', params, function(err, data) {
if (!err) {
following = data.relationship.source.following;
resolve(following);
} else {
reject(err);
}
});
});
};


Validation:

var validateMsg = function(dm) {
var sender = getSender(dm);
var result = [];
isFollowing(sender.id)
.then(function(response) {
if (!response) {
result = interactiveMessage(false, lang.__('FOLLOW_MAIN', sender.name));
console.log(result); // Displays as expected
return result; // Not returning value Do I need to return promise again? If yes, WHY?
}
});
};


Main Implementation:

var direct_message = function(msg) {
verifyAccount().catch(function(err) {
console.error(err);
});
var dm = msg.direct_message;
var result = validateMsg(dm);

console.log(result);
};


Questions is how should I force validateMsg function to return
result
variable inside
then
function.


Update: While debugging, I got to know that,
console.log(response)
in
validation function is displaying later after throwing undefined in
"then" function which means program is not able to get response
immediately and due to async nature, I/O is not getting blocked. How
to tackle this?

Answer

You're not actually returning anything in the validateMsg function. You're returning a synchronous value ( result ) in the .then function which is a separate function.

The second thing to consider is that you're expecting the validateMsg function, which is asynchronous to behave synchronously.

var result = validateMsg(dm);

The way to achieve what I believe you're looking to do involves making the following changes: 1) Return the promise chain in the validateMsg function.

    var validateMsg = function(dm) {
    var sender = getSender(dm);
    var result = [];
    return isFollowing(sender.id)
      .then(function(response) {
          if (!response) {
              result = interactiveMessage(false, lang.__('FOLLOW_MAIN', sender.name));
              return result;
          }
        // Not sure what you want to do here if there is a response!
        // At the moment you're not doing anything if the validation
        // is successful!
        return response;
    });

};

2) Change your function call, since you're now returning a promise.

    validateMsg(dm).then( function( result ){
      console.log( result );
    })

3) Consider adding a catch somewhere if only to help you debug :)

    validateMsg(dm).then( function( result ){
      console.log( result );
    })
    .catch( function( err ){
      console.log( "Err:::", err );
    });