0

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
user8321763
  • 149
  • 1
  • 11
  • use this link [enter link description here](https://stackoverflow.com/a/50581868/8101634) – primo May 30 '18 at 11:33

2 Answers2

2

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);
})
Deepak M
  • 849
  • 8
  • 17
  • Not working, error thrown at callback line - UnhandledPromiseRejectionWarning : ReferenceError : callback is not defined – user8321763 May 30 '18 at 07:27
  • Sorry, I forgot to add callback in function argument, it's working now thanks a lot – user8321763 May 30 '18 at 07:29
  • glad to help :) – Deepak M May 30 '18 at 07:30
  • I had a small doubt, is there any way that I make the execution flow stop at that position until it's processed. Because, in the above solution, if I write some command after h.holidays(....) line, the next line gets executed first instead of the h.holidays(...) line. Something such as await? – user8321763 May 30 '18 at 10:09
  • You can use [Async](https://www.npmjs.com/package/async). In your case I think async's [waterfall](https://caolan.github.io/async/docs.html#waterfall) method will be useful – Deepak M May 30 '18 at 10:35
  • Thanks, waterfall is so great! – user8321763 May 30 '18 at 12:41
1
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)
})