Search code examples
javascriptnode.jsasynchronous-javascript

Pass data from one js file to other synchronously in NodeJS


I have a situation where I need to service function in service folder from my controller folder and once I receive the output I need to pass it back to UI.

    //controller
    var service = require('service');
    api.get('/users', function(request, response) {
        var name = request.query['name'];
        var responseFromService = service.someAPI(name);
        response.send(responseFromService).status(200);
    });
    //Service


       exports.callTwitterAPI = function(twitterHandle,callback){
    var responseFromTwitterService;

    console.log("Calling Twitter API.." + twitterHandle);
    someAPI.get('users/show', {screen_name: twitterHandle}, function (err, data, res) {
        if (err) {
            //loggerError.error('No connection to twitter :', Date.now());
            responseFromTwitterService = JSON.stringify(err) + "Unable to connect twitter";
        } else if (data.errors) {
            responseFromTwitterService ="User Not Found!!"
           // loggerInfo.info('No Twitter handle found for :', twitterHandle);
        } else {
            console.log("here..");
            responseFromTwitterService = data;
        }
        console.log('response : '+ responseFromTwitterService);
        return (null,responseFromTwitterService);
    });
}

Now, I need to hold execution of

response.send(responseFromService).status(200);

this line until my service returns response, I need to make it synchronous.

Thanks in advance :)


Solution

  • Your service is going to either be synchronous by nature, or asynchronous by nature, and how you handle it will be determined by that.

    If the service call is synchronous, then what you've written will work fine. If it's asynchronous, then you'll just need to send your response in its callback, e.g.:

    //controller
        var service = require('service');
        api.get('/users', function(request, response) {
            var name = request.query['name'];
            var responseFromService = service.someAPI(name, function(err, responseFromService) {
                response.send(responseFromService).status(200);
            });
        });
        //Service
        exports.someAPI = function(name, callback){
        //some calculations
        return callback(null, responseFromService);
        }
    

    EDIT after your update

    Your service is never calling the callback you declared. Note your last line:

    return (null, responseFromTwitterService);
    

    Doesn't actually do anything. Instead you want:

    return callback(null, responseFromTwitterService);
    

    And then your calling code in the controller can be written as I suggested.