Reputation: 373
I've started using node.js a week ago and read through most questions here, as well as the docs. I'm still somewhat confused on how callbacks work exactly and can't get this particular code to work:
var someDomains = ['domain1.com', 'domain2.com', 'domain3.com'];
var someCnames = new Array();
function getCNAME (hostname, callback) {
dns.resolve(hostname, 'CNAME', function(error, cname) {
if (cname) {
callback(cname)
}
});
}
function saveCNAME(cname) {
// what to do here so that it saves into someCnames??
// when I try someCnames.push(cname) within this function, it..
// .. stores the cname only within this function. Console.log below..
// .. shows up as [].
}
someDomains.forEach(function(a) {
getCNAME(a, saveCNAME);
}
console.log(someCnames); // this should show a list of cnames
Basically, how do I modify someCnames which lives outside of the saveCNAME function from within saveCNAME? All examples that I find show stop with console.log(something) within the function, but I need to process someCnames outside of the saveCNAME function.
Upvotes: 0
Views: 62
Reputation: 1235
You should place that console.log in your saveCNAME function. You have most likely been saving those CNAMES, but your console.log is being invoked before the other calls to getCNAME and saveCNAME have been completed.
Upvotes: 1
Reputation: 39522
Keep track of how many callbacks have executed:
var someDomains = ['domain1.com', 'domain2.com', 'domain3.com'];
var someCnames = new Array();
var total = someDomains.length;
function getCNAME (hostname, callback) {
dns.resolve(hostname, 'CNAME', function(error, cname) {
if (cname) {
callback(cname)
}
});
}
function saveCNAME(cname) {
someCnames.push(cname);
total--;
if (total === -1) {
console.log(someCnames);
}
}
someDomains.forEach(function(a) {
getCNAME(a, saveCNAME);
}
(alternatively, you could use an async control flow library)
Upvotes: 2