0

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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
S.D.
  • 11
  • 1
  • 5
  • @T.J. Crowder I am sorry but I can't see how the link you posted can be used in this example! I tried many of the solutions, but is unclear to my how to get the asynchronous data – S.D. Dec 27 '16 at 11:31
  • 1
    If you have a specific problem implementing one of the solutions, then ask another question which (a) include an [mcve] of your attempt and (b) Includes a link to the answer you are trying to follow for context. – Quentin Dec 27 '16 at 11:34
  • `ip`/`ipExt` is simply not available *outside* of the `getIP` callback function; at least not *at the time* you're trying to use it. Because the callback is ***asynchronous***. As soon as you understand this fundamental problem your issue is solved. This has been explained more than sufficiently in the duplicate. – deceze Dec 27 '16 at 11:36

0 Answers0