javascript - Nodejs how to access Callback results outsite without setTimeouts? -
this question has answer here:
- how return response asynchronous call? 24 answers
i new nodejs , javascript. learning async programming. trying find ip address domain name. using nodejs inbuild "dns" library.
dns.resolve(domainname, function onlookup(err, addresses, family) { if (err){ res.send(err); } else { console.log(addresses); var domainaddress = addresses; } });
this actual code. trying domainaddress out of call back. since async programming, takes time domainaddress , unable access time.
if using code this, able access domainaddress
dns.resolve(domainname, function onlookup(err, addresses, family) { if (err){ res.send(err); } else { domainaddress = addresses; } }); settimeout(function() { console.log(domainaddress); }, 1000);
but not feel right way export result callback main program.
can please give alternate solution problem ?
note: want additional task once ip. want find geo location based on ip address. need pass ip separate module called geoip-lite. since unable address outside getting difficult
function myresolve(domainname, callback){ dns.resolve(domainname, function onlookup(err, addresses, family) { if (err){ return callback(err); } else { return callback(null, addresses); } }); } myresolve(domainname, function(err, addresses){ if(err){ return res.send(err); } else { return res.send(addresses); } });
please try code.
great
ReplyDelete