Hello Dear Developers,
I need your help.
I try to build weather app by using pure js only, without jQuery and etc. I have getLocation function, which should return location:
// API base url at http://ipinfo.io
var IPI_INFO_BASE_URL = "http://ipinfo.io/";
/**
* Retrieves the location for a given IP address(not necessary), using the ipinfo.io API.
*
* @param cb - The callback that handles the response.
* @param {string} ip address or 'json'.
* @return {Object.<string, string>} The location attributes and values, as defined in the API.
*
*/
function getLocation(cb, ip) {
var request;
if (window.XMLHttpRequest) { // Mozilla, Safari ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {}
}
}
request.open('GET', IPI_INFO_BASE_URL + ((ip) ? ip : ''), true);
request.setRequestHeader("Accept", "application/json");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200)
cb(JSON.parse(request.responseText));
else
console.log("Error location data");
}
};
request.send(null);
}
When I invoke this function with callback, which return data to console, it’s working good:
getLocation(function (response) {
console.log(response.city);
});
But when I try to assign return value to variable, the value of variable is “undefined”:
var currentLocation = getLocation(function (response) {
return response.city;
});
console.log(currentLocation);
What’s my mistake?
WBR
Denis