0

Say I have this function :

rest = require('restler');

function authenticate(credentials) {
   var accessToken;

   rest.post(BaseURL + '/Users/login', { data : credentials })
       .on('complete', function(result, response) {
               console.log(result.id); // this works fine
               accessToken = result.id;
        });

   return accessToken; 
};

I want it to return a string containing accessToken when I run this :

var at = authenticate({ "username": "test", "password" : "test" });
console.log('Access Token:', at);

I get Access Token : underfined

zianwar
  • 3,642
  • 3
  • 28
  • 37
  • 1
    The post function is async. The `return accessToken;` statement doesn't wait until the async call is done. So, it's returning what the initial value of accessToken is at that point. – 3abqari Jul 01 '15 at 01:48
  • 1
    You cannot do that. When your `authenticate` function returns, the callback has not been executed yet, and it won't be until the server replies. I'm sure someone will be able to point you at some resources here, but in the meantime try finding some documentation on asynchonous calls and working with Promises. – spectras Jul 01 '15 at 01:49

2 Answers2

4

The standard, accepted way, would be to modify the authenticate function:

function authenticate(credentials, cb) {
   rest.post(BaseURL + '/Users/login', { data : credentials })
       .on('complete', function(result, response) {
               console.log(result.id); // this works fine
               if (cb) { cb(result.id); }
           }
        });
};

and then execute it like this:

authenticate({ "username": "test", "password" : "test" }, function(at) {
    console.log(at);
});

Asynchronous calls must be handled with either a callback or a promise. Promises are "pretty" but are nothing more than callbacks. This is why you see almost every single Node API leveraging callbacks.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
0

You have a } spare in complete function:

rest.post(BaseURL + '/Users/login', {
    data: credentials
})
    .on('complete', function (result, response) {
    console.log(result.id); // this works fine
    accessToken = result.id;
}); // `}` spare here

Hope this help.

hungndv
  • 2,121
  • 2
  • 19
  • 20