Please someone enlighten me why the following returns an "undefined": I have looked and made various changes, but I always get errors!
var getIP = require('external-ip')();
var ip;
getIP(function (err, ipExt) {
if (err) {
// every service in the list has failed
throw err;
}
ip = ipExt;
});
console.log("External IP is: " + ip);
Honestly, I do not understand any of the explanations I have read and tried concerning callbacks. Here is one of my implementations using the callback. I am sure it is wrong, but I don't see why.
var getIP = require('external-ip')();
var asyncFunction = function(callback) {
var getIP;
getIP(function (err, ipExt) {
if (err) {
// every service in the list has failed
throw err;
}
getIP = ipExt;
callback (getIP);
});
};
asyncFunction(function(getIP){
console.log(getIP)
});
So I figured this out. Here is the final version. If anyone has any suggestion, please let me know!
var getIP = require('external-ip')();
var finalExtIP;
var myCallback = function(err, extIP) {
if (err) throw err; // Check for the error and throw if it exists.
//console.log('got data: '+ extIP); // Otherwise proceed as usual.
finalExtIP = extIP;
console.log(finalExtIP);
};
var getExtIP = function(callback) {
getIP(function (err, ip) {
if (err) throw err;
callback(null, ip);
});
};
getExtIP(myCallback);