1

So I have a file called 'myinternet_utils.js' and the following function:

exports.hasInternet = function () {

 require('dns').lookupService('8.8.8.8', 53, function (err, hostname, service) {
  return hostname;
 });

};

I also have a file called 'server.js', where I have this piece of code:

var ieUtils_ = require('./myinternet_utils.js');

console.log( ieUtils_.hasInternet() );

The 'console.log' prints 'undefined'.

Why am I not getting the output of the function hasInternet?

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – tkausl Feb 28 '19 at 10:47

1 Answers1

0

It seems like the function you are using is asynchronous. Also your function does not actually return anything, so even if it was synchronous you would still get undefined. Try this instead, using promises:

exports.hasInternet = function () {

    return new Promise(function(resolve, reject) {
        require('dns').lookupService('8.8.8.8', 53, function (err, hostname, service) {
            if(err){
                return reject(err);
            }
            resolve(hostname);
        });
    });

};

and in the main file

var ieUtils_ = require('./myinternet_utils.js');

ieUtils_.hasInternet().then(function(result){
    console.log(result);
})
Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35