0

Could someone tell me why my returned value is blank when the console.log returns the right answer?

I have a function that interates through a series of results and I'm trying to display the what3words name for the decimal degrees coordinates that I'm passing into this variable.

$.each(data.d.results, function (index, item) {
    var whatThreeWords = fnWhatThreeWords(item.Latitude,item.Longitude);
    //other code here to plot via leaflet
});

My fnWhatThreeWords looks like:

function fnWhatThreeWords(Lat,Lng) {
    var whatThreeWords = "";
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "https://api.what3words.com/v2/reverse?coords="+Lat+","+Lng+"&key=APIKEY&lang=en&format=json",
        error: function (err) {
            console.log(err);
        },
        success: function (data, status, xhr) {
            console.log(data.words);
            whatThreeWords = data.words;
        }
    });
    return whatThreeWords;
}

The console.log returns the appropriate response: "crumples.harmlessly.measuring" but when I return the whatThreeWords global function variable the result is empty;

var point = new L.marker([item.Latitude, item.Longitude], {icon: color}).bindPopup("<b>Residence "+Edit+"</b><br>RPA Id: "+item.RPAId+"<br>"+item.Address+"<br>what3words: "+whatThreeWords, {autoClose:false});
Xeverus
  • 125
  • 13

1 Answers1

1

To operate the whatThreeWords variable outside the ajax request you can set additional param async to your $.ajax() .But it's really a bad practice to prevent asynchronous code in js. What I'd suggest is to work with result inside the callback you assign to success property. That's the right way to do it.

To avoid callback in case you're going to make more asynchronous things inside other asynchronous ones, use Promises to organize code and make it more readable as it'll look like synchronous.

Abslen Char
  • 3,071
  • 3
  • 15
  • 29
  • Hey, I see that what3words has their own javascript wrapper with callbacks https://github.com/what3words/w3w-javascript-wrapper but if onSuccess: I return the data.words I still get a undefined. – Xeverus Mar 26 '18 at 15:59
  • use fetch or axios , i dont have experience with those plugin's I mainly use vanila js. – Abslen Char Mar 26 '18 at 18:09