0

Coming from a .net world where synchronicity is a given I can query my data from a back end source such as a database, lucene, or even another API, I'm having a trouble finding a good sample of this for node.js where async is the norm.

The issue I'm having is that a client is making an API call to my hapi server, and from there I need to take in the parameters and form an Elasticsearch query to call, using the request library, and then wait for the instance to return before populating my view and sending it back to the client, problem being is that the request library uses a callback once the data is returned, and the empty view has long been returned to the client by then.

Attempting to place the return within the call back doesn't work since the EOF for the javascript was already hit and null returned in it's place, what is the best way to retrieve data within a service call?

EX:

 var request = require('request');
 var options = {
   url: 'localhost:9200',
   path: {params},
   body: {
     {params}
   }
 }

 request.get(options, function(error, response){
    // do data manipulation and set view data
 }

 // generate the view and return the view to be sent back to client
Kaylee
  • 145
  • 1
  • 10

1 Answers1

1

Wrap request call in your hapi handler by nesting callbacks so that the async tasks execute in the correct logic order. Pseudo hapi handler code is as following

function (request, reply) {

    Elasticsearch.query((err, results) => {

        if (err) {
            return reply('Error occurred getting info from Elasticsearch')
        }

        //data is available for view


     });


 }

As I said earlier in your last question, use hapi's pre handlers to help you do async tasks before replying to your client. See docs here for more info. Also use wreck instead of request it is more robust and simpler to use

simon-p-r
  • 3,623
  • 2
  • 20
  • 35