Assigning a returned result for a function in a different file to a variable

55 Views Asked by At

I have a function in a utils file that I want to call and assign the exported result to a variable.

Currently, the variable is defined then I try to assign the return result but I am getting undefined as the result when I console.log it.

Here is my utils/consul file

var consul = require("consul")({host: config.consul.host'});
var consulBase = [];
var options;

module.exports = {
  consulQuery:  function(service){
      consul.catalog.service.nodes(service, function(err, results) {
          if(err) {console.log(err); throw err;}
           if(results.length <= 0) return {message: `Error could not find any service of ${service} registered with consul,`, errorCode: 500};
          if(results.length > 0) consulBase = [];
          results.forEach((result) => {
            consulBase.push(result.ServiceAddress+ ':' +result.ServicePort);
          });
          var serviceURL = 'http://' + consulBase[Math.floor(Math.random()*consulBase.length)];
          return options = {
            baseUrl : serviceURL,
            form: {'':''},
            headers: {authorization: ''}
          };    
        });
    }

Then in another file, I am calling like this and then trying to assign the value to 'options' but am getting undefined.

var consulQuery = require("../utils/consul").consulQuery;

// Get options array right away
var options = consulQuery('auth');

// Get options array every 5 seconds
setInterval(() => {
  options = consulQuery('auth');
  console.log(options);
}, 5 * 1000);
1

There are 1 best solutions below

2
lrossy On

OK you have a couple issues.

First, is conceptual about what you are trying to do. Second is what do you actually need to change in your code to make it work.

I will not talk about the first part because, and there are plenty of good resources to learn about async with examples better then I can do here.

For the actual problems with your code:

  1. You are missing a callback for consulQuery()

It should be something like this (notice the cb i added):

module.exports = {
    consulQuery: function (service, cb) {
        consul.catalog.service.nodes(service, function (err, results) {
            if (err) {
                console.log(err);
                cb(err, null)
                throw err;
            }
            if (results.length <= 0) return {
                message: `Error could not find any service of ${service} registered with consul,`,
                errorCode: 500
            };
            if (results.length > 0) consulBase = [];
            results.forEach((result) => {
                consulBase.push(result.ServiceAddress + ':' + result.ServicePort);
            });
            var serviceURL = 'http://' + consulBase[Math.floor(Math.random() * consulBase.length)];
            cb(null, {
                baseUrl: serviceURL,
                form: {'': ''},
                headers: {authorization: ''}
            });
        });
    }
}

Second, in the other file in which you invoke the function, you will have to now pass a callback function.

options = consulQuery('auth', (err, response) => {
if(err){
console.log(err)
}
console.log(response)

});