1
\$\begingroup\$

How can I combine multiple DNS lookups without nesting a whole bunch of if else statements? How would this impact performance? I would ultimately like the function to lookup all DNS addresses simultaneously.

function checkInternet(isConnected) {
    require('dns').lookup('a.root-servers.net', function (err) {
        if (err && err.code == "ENOTFOUND") {
            require('dns').lookup('b.root-servers.net', function (err) {
                if (err && err.code == "ENOTFOUND") {
                    isConnected(false);
                } else {
                    isConnected(true);
                };
            });
        } else {
            isConnected(true);
        }
    });
};
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You could launch all the operations in parallel and then call the callback when the first one succeeds or when all have failed. Here's a way to do that:

function checkInternet(callback) {
    var servers = ['a.root-servers.net', 'b.root-servers.net'],
        lookup = require('dns').lookup,
        complete = false, doneCnt = 0;

    function done(err) {
        ++doneCnt;
        if (!complete) {
            if (err) {
                // if we got an error here and we're done with all of them
                // then all connections failed
                if (doneCnt === servers.length) {
                    callback(false);
                }
            } else {
                // this one completed successfully
                complete = true;
                callback(true);
            }
        }
    }

    // start all dns lookups in parallel
    servers.forEach(function(s) {
        lookup(s, done);
    });
}

FYI, I did not check only for the specific error "ENOTFOUND" like you were doing. If there's any error, then the DNS check did not succeed so in this type of structure, it seems you're looking for any single success or all of them failed (no matter why they failed).

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.