I am working with a node.js
application that uses Facebook APIs. In one part of my code I need to return the access_token
from a common function. That is, a lot of other functions need to call this function to retrieve the Facebook access token.
Below is my code:
function getAccesstoken(code) {
var options = {
host: 'graph.facebook.com',
path: '/oauth/access_token?client_id=xxxx&redirect_uri=xxxxxx&client_secret=xxxxx&code='+code.toString()
};
var acc_token = ''
https.get(options, function(resp) {
resp.on('data', function(d) {
acc_token = acc_token+d.toString()
});
resp.on('end', function() {
var expiry_index = acc_token.indexOf('&expires=')
acc_token = acc_token.substring(0, expiry_index)
});
});
return acc_token.toString()
}
Since https.get
call is asynchronous, function always returns an empty string. What should be the best way to do this?
You've already answered the question in your title - use a callback.
Define another variable for getAccesstoken
that should be a function that gets called when acc_token
is filled, and pass acc_token
as an argument for that function to use.
It's the same way that https.get
is working - the second argument is a function that's called when the request is completed, and gets passed the result of the request.
well supply a callback function to your getAccesToken function and call the function after the response has ended and pass acc_token to that function..
function getAccessToken(code,cb){
.....
resp.on('end',function(){
.....
cb(null,acc_token)
})
}
then call your function like
getAccesToken("whatever",function(err,token){
console.log("got token", token)
})