0

i'm writing a Web Service in node and i'm new with callbacks concept. I have in my routing file a route that receives url param - a Facebook access token, and should call the getMP function. This function creates http request to Facebook and retrieve some info I want to process later. so the route looks like this:

//route that recives parameter using defined parameters - enter FB access token to get  music info about it
app.get('/MP/:FBat', 
    function (req, res, next){
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next(); 
    },

    function (req, res) {
    res.status(200).json(FB.getMP(req.params.FBat));
});

and the function getMP :

exports.getMP = function(access_token) {
request("https://graph.facebook.com/v2.5/me/music?access_token=" + access_token, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        FB_MP = JSON.parse(body);
        // console.log(FB_MP); this returns ok
      }else{
        console.log(response.statusCode);
      }
    });

//return value - I wand to use it after the request has returned
return FB_MP;
}

What is the correct way of doing this? It works if the res is fast but of course its not good. any advice ? thanks

1
  • You need to keep it mind that javascript is asynchronous language, callback is the primary way of preserving function execution order by injecting the function into the another function Commented Feb 24, 2016 at 15:20

1 Answer 1

1

You can use a library for promises like q and make the response after you get the necessary value inside the method then, try something like this:

//route that receives parameter using defined parameters - enter FB access    token to get  music info about it
app.get('/MP/:FBat', 
    function (req, res, next){
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next(); 
    },

    function (req, res) {
        FB.getMP(req.params.FBat)
        .then(function(result){
            if(result){
                res.status(200).json(result);
            }
            else{
               console.log('do something about it');
            }
        });            
});

the code of getMP will be something like this:

var Q = requirie('q');
exports.getMP = function(access_token) {
    var deferred = Q.defer();
    request("https://graph.facebook.com/v2.5/me/music?access_token=" +  access_token, function(error, response, body) {
     if (!error && response.statusCode == 200) {
        FB_MP = JSON.parse(body);
        deferred.resolve(FB_MP);
      }else{
        deferred.resolve(false);
      }
    });

    //return value - I wand to use it after the request has returned
    return deferred.promise;
}

Also you can pass the req and res params to a kind of controller where you put the logic and then send the result to the view. Something like this:

//route that receives parameter using defined parameters - enter FB access  token to get  music info about it
var controller = require('path/to/controller');
app.get('/MP/:FBat', 
    function (req, res, next){
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next(); 
    },

    function (req, res) {
        controller.getFacebookAccess(req, res, req.params.FBat);
});

The controller:

module.exports = function getFacebookAccess(req, res, access_token){
    request("https://graph.facebook.com/v2.5/me/music?access_token=" +  access_token, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            FB_MP = JSON.parse(body);
            res.status(200).json(FB_MP);
          }else{
            res.send('do something about it');
          }
        });
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.