0

I'm using hapi and memcached in my node service :

var usrarray=[];
const server=Hapi.server({
    host:'localhost',
    port:8080
});
server.route([
  {
    method : 'POST',
    path:'/getdata',
    handler : function(request,reply){

            var usr=request.payload.usr;
            var arr = usr.split(",");
            var p=getdata(arr);
            p.then(function(data){
                console.log(data);
            }).catch(function(err){

                console.log(err)            
            });         

       //return data;
    }
  }
]);

function getdata(arr)
{

    try{
        return new Promise
        (  (resolve,reject)=> {

                for(var i=0;i<arr.length;i++)
                {

                    var user=arr[i];
                    cached.get(user)
                    .then((data) => {
                        if(data)
                        {                       
                            usrarray.push(data);
                        }

                    }, (err) => {
                        console.log(err);
                        return reject(err);
                    })
                    if(i==(arr.length-1))
                    {
                        return resolve(usrarray);
                    }

                }
            }
        )
    } catch(err) {
        console.error(err)
        return err;
    }
}

This is the payload json that I POST to the above service through postman

{"usr":"2,22"}

When I hit the url in postman the node service prints a blank response. This is the code snippet from the above code where the data is being printed :

 p.then(function(data){
    console.log(data); //this prints the data returned by the promise in `getdata(arr)` function
   }

When I hit the url for the second time it prints the correct result. It always prints the correct result after the first time. I get a blank response only when I hit the url for the first time. I'm getting data from memcache on the first url hit.

So I'm not able to figure out why the function getdata(arr) returns a blank response when I hit url for the first time. What's wrong with my code?

node_man
  • 1,359
  • 4
  • 23
  • 50
  • Related: https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – T.J. Crowder Mar 12 '19 at 11:11
  • Your `handler` function **can't** `return` the data from an asynchronous operation. Whatever this `server.route` function is, presumably it provides a way for your handler to supply the response asynchronously. (In Express or Koa it's part-and-parcel of how they work, you call `send` on a response object, and the call doesn't have to be during the call to the route handler.) – T.J. Crowder Mar 12 '19 at 11:14
  • ok thank you I'll go through the links – node_man Mar 12 '19 at 11:20

0 Answers0