Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js DNS response delayed

I'm just trying to concatenate an array containing domains that are the result of a DNS resolution.

This is my code :

        var ipList = [];
        for(var j=0; j < addressList.length; j++) {
            dns.resolve(addressList[j], function(error, ipRange) {
                if(error !== null) {
                    console.log('The DNS request failed.');
                }
                console.log('--1--');
                console.log(ipRange);
                console.log('--2--');
                ipList.concat(ipRange);
            });
        }

        console.log(ipList);

The result I'm getting is this :

[]
--1--
[ '173.194.35.144',
  '173.194.35.145',
  '173.194.35.146',
  '173.194.35.147',
  '173.194.35.148' ]
--2--

It looks like the DNS resolution response arrives after the concat(), like it was delayed. Which means that ipList is an empty array.

Can anyone help me on this ? Thanks in advance !

like image 378
m_vdbeek Avatar asked Dec 03 '25 13:12

m_vdbeek


1 Answers

resolve is async, so it's not done when you do the final print. Use synchronous DNS (can't find this for node.js immediately), or arrange your callbacks properly.

like image 171
Matthew Flaschen Avatar answered Dec 06 '25 10:12

Matthew Flaschen