1

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?

Navi
  • 95
  • 2
  • 8
  • 3
    See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call and http://stackoverflow.com/questions/2190850/create-a-custom-callback-in-javascript. – Felix Kling May 04 '14 at 22:43
  • You can't return the answer from your `dnsCheck()` function because `dns.lookup()` is asynchronous and it returns sometime AFTER `dnsCheck()` 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 into `dnsCheck()` and call that callback when you get the `dns.lookup()` results. That is async programming and how you have to do it with async operations. – jfriend00 May 04 '14 at 22:49
  • Yep. What you are asking is a sizeable task. I'll provide the answer for callbacks (and maybe promises) below. – Johnny Hall May 04 '14 at 23:04

1 Answers1

0

Callbacks (same as the other question).

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

// Let's assume domainValidate is async too
var domainValidate = function(domain, tld, callback) {
  return callback(true);  // Add your logic here
};

dnsCheck(domain, tld, function(isChecked) {
  domainValidate(domain, tld, function(isValid) {

    if (isChecked && isValid) {
      res.end('available');
    } else {
      res.end('unavailable');
    }
  });
});

Promises (I don't know Q, but you get the idea, I hope).

var dnsCheck = function(domain, tld) {
  return new Promise(function(resolve, reject) {
    require('dns').lookup(domain + '.' + tld, function (err, addresses) {
      if (err) return reject();
      resolve();
    });
  });      
};    

// Domain validate will be similar  

dnsCheck(domain, tld).then(function() {
  return domainValidate(domain, tld);
})
.then(function() {
  res.end('available');
})
.catch(function() {
  res.end('unavailable');
});

I'll leave someone else to show how it's done with generators. I'm not as familiar with them as I am promises.

Johnny Hall
  • 545
  • 4
  • 12