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?