1

I'm using the Yelp API to get a list of businesses in a certain area. I call my function 'searchForBusinesses()' which makes a request to my backend server code and gets a response in the form of a list of 10 businesses.

function searchForBusinesses(parameters){

    var businesses = [];

    $.get('yelp', parameters, function(res){

        for(var i = 0; i < 10; i++){

            var business = {
                title: res.businesses[i].name,
                location: { lat: res.businesses[i].coordinates.latitude, lng: res.businesses[i].coordinates.longitude },
                id: res.businesses[i].id
            };

            businesses.push(business);

        }            

    });

    return businesses;
}

When I call my function

var businesses = searchForBusinesses(parameters);
console.log(businesses);
console.log(businesses.length);

I get

this result

For some reason, I can log the list with all of the businesses in there correctly, but when I log the length of that list, I get 0. This is highly unusual.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
dimitri
  • 11
  • 1
  • 3
  • 1
    [__How do I return the response from an asynchronous call?__](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Rayon Jul 07 '17 at 09:48
  • 1
    `$.get` is an asynchronous function. When your function returns, `businesses` is indeed an empty array and hence its length will be 0. However, when logging the array, you pass a reference to that array and the inspector will allow you to inspect the *current state* of the array. Since by the time of inspection, the request has completed, you are now able to view the array contents. – Just a student Jul 07 '17 at 09:49

0 Answers0