Wednesday, 26 April 2017

Use a variable from one function in a different module node JS

I need to take out data from a API call and use the variable values in a different function in a different class. However, when I run Node, the callback takes 'x' amount of seconds to come through. So this is what I though of:

**callback.js

var status = require('../consumer.js')

    router.post('/callback', function(req, res) {
        var reqBody = req.body;
        if (reqBody != undefined) {
            status(reqBody);
        } else {
            console.log('reqBody does NOT contain data')
        }
     })

**consumer.js

The status function is exported from this class so that the callback.js class can make use of it

    function status(passedData) {
      console.log(passedData);   // prints out correctly
    }

The handle message function is within the same class (consumer.js) however lower down, where a different functions invokes the handleMessage function.

function handleMessage(data, done) {
  request({url: "http://test.com",method: "POST",body: data }, 
    function(error, response, body) {

    parseString(response.body, function(err, result) {

      function myResult(?) {
          console.log(passedData) // I need to make use of the passedData variable in here
          done();
        }
      }
    });
  });
}

So, any idea how I can use reqBody in the myResult function?

I have tried calling it directly in the function, and making a global variable, but the it always came back as undefined - because consumer.js has already run and callback.js has only just started - i.e. we need to wait for the callback.js to receives the reqBody before consumer.ja can continue.

Any help will be appreciated!



via deeveeABC

No comments:

Post a Comment