I know there have been many similar questions before, but I've tried every single one and still getting this specific problem in every try. So what I'm doing is I have a file called data.js that contains a function which fetches json data from web api and return Json parsed string. I have another file that calls this function and simply I'm trying to debug the result on console. But everytime I run the function I'm getting 'undefined' on console, i.e the code is running asynchronously and value is getting returned even before it's fetched. Here's my code:
data.js
module.exports = {
holidays: function(x,y,z)
{
function intialize()
{
return new Promise(function(resolve, reject) {
Request.post({
"headers": { "content-type": "application/json" },
"url": //someurl,
"body": JSON.stringify({//some input})
}, function(err, resp, body) {
if (err)
{
reject(err);
}
else
{
resolve(JSON.parse(body));
}
})
})
}
var Request = require("request");
var json_content="";
var req = intialize();
req.then(function(result) {
console.log(result);//getting correct answer here
json_content=result;
//I know I've to return the value somewhere here but how do i do it
}, function(err) {
console.log(err);
});
return(json_content);
}
};
The code in calling function:
var h= require(__dirname+'/data.js');
console.dir(h.holidays('x','y','z'));//getting undefined