Part of weather app

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

Your function getLocation() doesn’t return anything.

And no you can’t just add return to your getLocation() :wink:

Read this: javascript - How do I return the response from an asynchronous call? - Stack Overflow

Thank you!
I think the callback function should return a value), but I see that it is not so easy to do. Thanks for a link but I still no idea how to upgrade my function.

You could something do like this:

function getLocation() {
  ...
  if (request.status == 200) doStuff(someData);
  ...
}

function doStuff(someData) {
  // do something
}

getLocation();

Example: http://codepen.io/jenovs/pen/vgdbLL?editors=0011

1 Like

Thank you so much, @jenovs. You helped me a lot, but the problem is… I have another function(getWeather) which use location data(city name) from getLocation function. And I need to store location date to variable and then set the variable to getWeather function.
I haven’t problem to append location data to html, I need to append the data to variable. I try to fix it few day’s but nobody know how to do. I think it is a big secret)

@jenovs, thank you. I fixed it. :nerd: