0

I'm trying to return boolean answer from function and want to check with if-else statements.

function dnsCheck(domain,tld) {
    var dns = require('dns')
    dns.lookup(domain+'.'+tld, function (err, addresses) {
        if (err) return false // means domain not registered
            else return true // means domain registered
    })
}

my conditional statement:

if(domain_validator(domain,tld) && dnsCheck(domain,tld)) {
    res.end("avl")
}
else {
 res.end("not avl")
}

The first function alone works in the if statement but when I add 2nd function "dnsCheck", it fails to work as expected. Am I missing something?

Navi
  • 95
  • 2
  • 8
  • 3
    `dns.lookup` looks asynchronous. So `return false` or `return true` does not return that value to anything. Since you have to run an asynchronous code, you have to refactor your code and send callbacks or promises everywhere instead of simple function calling. – PhistucK May 03 '14 at 11:40
  • how are you calling this function? – Sumit Bisht May 03 '14 at 11:40
  • Thanks @PhistucK, let me refactor the code keeping in view the sync nature of that function. Are all core node.js functions async? How would I know if a particular function is async or sync? – Navi May 03 '14 at 11:45
  • A synchronous function simply returns a value. An asynchronous function expects a callback function as a parameter. – PhistucK May 03 '14 at 11:49
  • Have a look at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call to learn about the problem and possible solutions. It applies to all async functions, not only Ajax. – Felix Kling May 03 '14 at 12:59
  • I am still not able to use the callbacks successfully, what would be the best approach if I'm just starting our async style of coding? callbacks, promises or generators as in Koa.js? Could you guys please provide me the sample code for the above function dnsCheck and checking condition after? – Navi May 04 '14 at 22:14

1 Answers1

0

Rewrite dnsCheck like this:

function dnsCheck(domain, tld, callback) {
  var dns = require('dns')
  dns.lookup(domain + '.' + tld, function(err, addresses) {
    callback(err == null);
  });
}

Then call it like this:

dnsCheck(domain, tld, function(isValidDns) {
  if (isValidDns) {
    // Profit...
  }
});

It's likely that the other function domain_validator is/should be async too.

Not all functions are async, but if you want to know if it is, then the signature of the function will (generally) have a function as the last parameter, with (usually) a signature of function(err, result), as dns.lookup does.

Try reading about node.js callbacks. This is one such explanation:

http://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks

Johnny Hall
  • 545
  • 4
  • 12