jQuery在继续之前等待函数的返回值

时间:2019-11-05 03:24:05

标签: javascript jquery asynchronous callback return

我有一个函数,该函数包括对另一个函数的调用,该函数返回一组坐标。但是,当调用此函数时,它不等待坐标的返回,而是继续,并且当我尝试打印返回的值(数组)时,始终是未定义的。如何强制我的代码等待坐标返回?

被称为的地方:

$('#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 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);
  }
}

1 个答案:

答案 0 :(得分:0)

您正在处理的事情称为“异步调用”,这意味着您必须等到 Promise 返回后才能继续进行工作。

对于jQuery,我认为仅使用Promise就足够简单了,但是您应该仔细阅读这一类别,因为如今它非常流行。 (评论中已经提供了链接)

您的代码应如下所示:

$('#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)
      })

});