ckorvee
ckorvee

Reputation: 87

Jquery Wait for Return Value of Function before Continuing

I have a function that includes a call to another function which returns a set of coordinates. However, when this function is called, it doesn't wait for the return of the coordinates, instead it continues, and when I try to print the returned value(an array), it is always undefined. How can force my code to wait for the return of the coordinates?

Where it's being called:

$('#arena-form').on('submit', function(e) {
    e.preventDefault();
    fullAddress = "80 Devon Street, Brantford, Ontario, Canada";

    var locationInfo = [];
    locationInfo = geocodeQuery(fullAddress); // calling the function that will return the coordinates

    console.log(locationInfo);

});

Function that Returns the Coordinates

function geocodeQuery(address) {
    if (!searchManager) {
      Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
      searchManager = new Microsoft.Maps.Search.SearchManager(map);
      geocodeQuery(address);
    });
    } else {
        var searchRequest = {
            where: address,
            callback: function (r) {
                if (r && r.results && r.results.length > 0) {
                    var locationInfo = [r.results[0].location.latitude, r.results[0].location.longitude];
                    return(locationInfo);
                }
            },
            errorCallback: function (e) {
                showModalAlert("danger", "location not found");
            }
        };

      //Make the geocode request.
      searchManager.geocode(searchRequest);
  }
}

Upvotes: 0

Views: 705

Answers (1)

Duc Hong
Duc Hong

Reputation: 1179

What you're dealing with is called Asynchronous Call, this simply means you have to wait until the a Promise is returned to proceed further with your work.

For jQuery, I think it's simple enough to use just Promise, but you should read up on this category because nowadays it becomes quite popular. (link is already provided in comment)

Your code should be look like this:

$('#arena-form').on('submit', function(e) {
    e.preventDefault();
    fullAddress = "80 Devon Street, Brantford, Ontario, Canada";

    const promised = new Promise(function(resolve, reject) {
      const locationInfo = geocodeQuery(fullAddress);

      if (!locationInfo) {
        return reject('Your reason')
      }

      return resolve(locationInfo)
    })
    

    promised
      .then(function(result) {
        console.log('Location info: ', result);
      })
      .catch(function(error) {
        console.log('Error: ', error)
      })

});

Upvotes: 1

Related Questions