Reputation: 149
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
Upvotes: 0
Views: 70
Reputation: 255
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="";
return new Promise(function(resolve, reject) {
intialize()
.then(function(result) {
resolve(result);
})
.catch(function(err) {
reject(err);
});
});
};
And you have to get the response like
var h= require(__dirname+'/data.js');
h.holidays('x','y','z').then(function(res) {
console.log(res)
})
Upvotes: 1
Reputation: 849
its very simple. You have to use callback functions to fetch results.
module.exports = {
holidays: function(x,y,z,callback){
function intialize()
{
return new Promise(function(resolve, reject) {
Request.post({
"headers": { "content-type": "application/json" },
"url": //someurl,
"body": JSON.stringify({ })
},
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);
json_content=result;
callback(json_content); // sending response from here via callback variable
}, function(err) {
console.log(err);
});
return(json_content);
}
};
And you have to get the response like
var h= require(__dirname+'/data.js');
h.holidays('x','y','z',function(res){
console.log(res);
})
Upvotes: 2