Skip to content Skip to sidebar Skip to footer

Usage Of Callback Functions And Asynchronous Requests

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

Solution 1:

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..

functiongetAccessToken(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)
})

Solution 2:

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.

Post a Comment for "Usage Of Callback Functions And Asynchronous Requests"