使用$ timeout

时间:2016-10-28 20:36:22

标签: javascript angularjs recursion

我在AngularJS中创建了一个递归函数调用,只是想知道有没有更好的方法来解决这个问题?

我的代码如下:

function getLocation(query, map, object, delay) {
    var deferred = $q.defer();
    var service = new google.maps.places.PlacesService(map);
    service.textSearch({ query: query }, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            var loc = results[0].geometry.location;
            object.lang = loc.lng();
            object.lat = loc.lat();
            deferred.resolve(object);
        } else {
            if (status === "OVER_QUERY_LIMIT") {
                delay += 100;
                deferred.resolve($timeout(function () {
                    var deferred = $q.defer();
                    getLocation(query, map, object, delay).then(function (object) {
                        deferred.resolve(object);
                    });
                    return deferred.promise;
                }, delay));
            } else {
                deferred.reject(status);
            }
        }
    });
    return deferred.promise;
}

1 个答案:

答案 0 :(得分:0)

当你调用deferred.resolve($timeout(function () { ...时,你说你的promise功能已经成功解决,你返回$ timeout(它本身就是一个promise)promise对象,而不是预期的{lang:..., lat:...}对象。这听起来不正确。然后在$timeout内开始新的promise函数调用。

我会尝试返回$ timeout保证,而不是解析它,并在getLocation(...)内调用$timeout.then()函数,我也会返回deferred.resolve(object)而不是执行:

function getLocation(query, map, object, delay) {
  var deferred = $q.defer();
  var service = new google.maps.places.PlacesService(map);
  service.textSearch({ query: query }, function (results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var loc = results[0].geometry.location;
        object.lang = loc.lng();
        object.lat = loc.lat();
        return deferred.resolve(object);
    } else if (status === "OVER_QUERY_LIMIT") {
      delay += 100;
      return $timeout(function () {}, delay).then(function () {
        return getLocation(query, map, object, delay);
      });
    } else {
      deferred.reject(status);
    }
  });
  return deferred.promise;
}