0

I'm building an MVC application in Node, Express, Request...etc with a controller to repository stack. In the repo, I'm connecting with request (Simplified HTTP request client) to an external API that returns JSON.

I have the following code:

// The repository
var request = require('request');

module.exports.getById= function (id) {

    var options = {
        url: 'http://myurl...' + id,
        headers: {
            'Accept': 'application/json',
             'Accept-Language': 'en-US',
         }
    };

    request(options, callback); 

    function callback(error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = JSON.parse(body);
                return data;                        
        } else {
            res.send(404); // HTTP STATUS
             console.log("ERROR: " + error);
        }
    }   
};

// The Service
var myRepository = require('../repositories/myRepository');

module.exports.getById = function (id) {

    return myRepository.getById(id);
};

How do I return data to the service, that returns it to the controller that renders it in the view? Return data from within the callback doesn't work. It also seems that I can't pass an additional callback method to the request callback in order to return it.

scniro
  • 16,844
  • 8
  • 62
  • 106
Victor
  • 359
  • 1
  • 6
  • 14
  • You should pass the callback to your method and invoking it with the data you receive in the callback to the service call – Vsevolod Goloviznin Jan 10 '15 at 20:38
  • 1
    You don't return data from an async callback. Instead, you use the data in the callback itself (e.g. your code continues in the callback), not after the callback. This is how async development works. – jfriend00 Jan 10 '15 at 21:32
  • Could you give me an example, I'm not sure how you mean? – Victor Jan 10 '15 at 21:54

0 Answers0