0
function getSenderName(senderId) {
      var __name;
      // Get user's first name from the User Profile API
      // and include it in the greeting
      request({
        url: "https://graph.facebook.com/v2.6/" + senderId,
        qs: {
          access_token: process.env.PAGE_ACCESS_TOKEN,
          fields: "first_name"
        },
        method: "GET"
      }, function(error, response, body) {
        if (error) {
          console.log("Error getting user's name: " +  error);
        } else {
          var bodyObj = JSON.parse(body);
          __name = bodyObj.first_name;
          console.log("1.SenderId : " + senderId + " Name : " + __name);
        }
      });
      console.log("2.SenderId : " + senderId + " Name : " + __name);
      return __name;
    }

with above code i get

1.SenderId : 1234 Name : Vinay
2.SenderId : 1234 Name : Undefined

can anybody help me in how to access variable which is inside such nested function

vjain419
  • 243
  • 1
  • 3
  • 11
  • 1
    it's nothing to do with `nested function` - it's to do with asynchronous code - and I **bet** you get 2 output before 1 – Jaromanda X Apr 27 '17 at 06:31
  • @JaromandaX Yes! true..I am very new to javascript. is there any way I can get "Vinay" in both – vjain419 Apr 27 '17 at 06:33

1 Answers1

1

Just for you to know that,

function getSenderName(senderId, callback) {
  function(){
    var variable ;
   //some stuff
    callback(variable, otherArgs ...);
  }
}

callbacks does the exactly same jobs..

  • so how does getSenderName call will look like!? – vjain419 Apr 27 '17 at 06:36
  • 1
    Pass the callback function, do whatever you want to do, then execute that callback function with the parameters you would like to have. Also check out the MDN documents for callbacks. –  Apr 27 '17 at 06:39