I understand there may be duplicate threads on this so I apologise in advance, however, I cannot seem to either find the right thread to help me, or more so, get my example to work...
What I am trying to do
I am trying to execute JavaScript code in my AngularJS app that obtains my local IP address, and I want to get this IP address before anything else is executed.
I have placed this code in my app.run()
module at the very beginning and then have other code directly under it like this example:
app.run(function() {
function getIP() {
var myIP = '';
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;//compatibility for Firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel('');//create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop);// create offer and set local description
pc.onicecandidate = function(ice)
{
if (ice && ice.candidate && ice.candidate.candidate)
{
myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
pc.onicecandidate = noop;
return myIP;
}
};
}
var ip = getIP();
console.log(ip);
console.log('Starting App');
//Do some stuff
console.log('Launching');
});
The result I get is:
undefined
Starting App
Launching
Obviously the code behind obtaining the IP Address takes time to execute and JavaScript is continuing to execute the remaining code in the module. However, I'm not sure how to overcome this correctly. I have tried using promises
and callbacks
and factories
but doesn't seem to make much difference for me.
Am I doing something wrong? Do I need to put all remaining module code in a separate function maybe? I'm thinking it has something to do with the function inside the function in getIP()