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 !
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.
You can do something like this where you keep track of the number of DNS queries still outstanding so that you can tell when the full set is available:
var ipList = [], count = addressList.length;
for(var j=0; j < addressList.length; j++) {
dns.resolve(addressList[j], function(error, ipRange) {
if(error !== null) {
console.log('The DNS request failed.');
} else {
ipList.push(ipRange);
}
if (--count === 0) {
// All DNS queries are complete.
console.log(ipList);
}
});
}