My function:
function dnsCheck(domain,tld) {
var dns = require('dns')
dns.lookup(domain+'.'+tld, function (err, addresses) {
if (err) return false // means domain avl
else return true // means domain not avl
})
}
My conditional statement:
if(domain_validator(domain,tld) && !dnsCheck(domain,tld)) {
res.end("avl")
}
else {
res.end("not avl")
}
domain_validator function is just a regex checker and returns true if it passes else false.
I am using express framework. How do I refactor my code using callbacks, promises (Q library) or generators (koa framework) to play nicely with async "dns.lookup" function? Could anyone please modify my code using all the three approaches?
dnsCheck()function becausedns.lookup()is asynchronous and it returns sometime AFTERdnsCheck()has already finished and returned. Your current return value is just being returned deep into the bowels of the network handling code and going nowhere. You probably want to pass a callback intodnsCheck()and call that callback when you get thedns.lookup()results. That is async programming and how you have to do it with async operations.