0

I am trying to receive an array of results from a function as follows:

getSearchLocation(){
    let results = [];
    geocoder.geocode( { 'address': address}, function(results, status) {
        console.log("in scope", results);
        return results;
    });
console.log("out of scope", results);
}

"in scope" results returns the array as it should be.

"out of scope" results returns a length: 0 empty array.

If I returned results array from geocoder.geocode(), isn't it supposed to assign it to the declared results array in getSearchLocation()?

Thanks, Bud

clusterBuddy
  • 1,523
  • 12
  • 39
  • @HassanImam - thx for reference. do I need to chain `.then()`? – clusterBuddy Apr 23 '18 at 13:10
  • You can return a promise from your function `getSearchLocation()`, resolve it inside `then()` in the function where you are calling it. You can also use `async -await`. – Hassan Imam Apr 23 '18 at 13:11

1 Answers1

0

getSearchLocation(){
    let results = [];
    geocoder.geocode( { 'address': address}, function(results, status) {
        console.log("in scope", results); <== Line 1
         
    });
console.log("out of scope", results); <== Lin 2
}

Take a look at the lines that I marked in the snippet. In Line 1, you are logging the results of callback of geocoder.geocode while in line 2 you are logging the empty array you just declared above. \

Moreover if you are assuming that it would contain the results you better assign the return value to it. Something like

getSearchLocation(){
    let results = [];
    geocoder.geocode( { 'address': address}, function(data, status) {
        results = data;
        console.log("out of scope", results);
        
    });

}
Muhammad Usman
  • 10,039
  • 22
  • 39
  • hey George, I liked what you wrote, thanks, but the last line there: `console.log("out of scope", results);` is still in scope, with this construct, how would I be able to assign `geocoder.geocode()` results to `getSearchLocation()` results? – clusterBuddy Apr 23 '18 at 13:29