javascript - Pass data from one js file to other synchronously in NodeJS -


i have situation need service function in service folder controller folder , once receive output need pass 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 twitter :', date.now());             responsefromtwitterservice = json.stringify(err) + "unable connect twitter";         } else if (data.errors) {             responsefromtwitterservice ="user not found!!"            // loggerinfo.info('no twitter handle found :', twitterhandle);         } else {             console.log("here..");             responsefromtwitterservice = data;         }         console.log('response : '+ responsefromtwitterservice);         return (null,responsefromtwitterservice);     }); } 

now, need hold execution of

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

this line until service returns response, need make synchronous.

thanks in advance :)

your service going either synchronous nature, or asynchronous nature, , how handle determined that.

if service call synchronous, you've written work fine. if it's asynchronous, you'll need send response in 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 update

your service never calling callback declared. note last line:

return (null, responsefromtwitterservice); 

doesn't anything. instead want:

return callback(null, responsefromtwitterservice); 

and calling code in controller can written suggested.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -