AngularJS:如何用延迟调用递归函数

AngularJS: how to call recursive function with a delay?

本文关键字:调用 递归函数 延迟 何用 AngularJS      更新时间:2023-09-26

我有这样的功能:

$scope.getContactsByScroll = function() {
  $scope.pageN = $scope.pageN + 1;
  if (!$scope.allDataIsLoaded){
    fetchMyDataService.getContactsByScrollService($scope.pageN).then(function(response) {
      if (response.length === 0){
        $scope.allDataIsLoaded = true;
      }
      else if (response.length !== 0 && !$scope.allDataIsLoaded){
        angular.forEach(response, function(el) {
          $scope.contacts.push(el);
        });
        //$timeout(function() {
          $scope.getContactsByScroll();
        //}, 2000);
      }
    }).catch(function() {
      $scope.allDataIsLoaded = true;
    });
  }
};

但它甚至多次称呼自己,如果$scope.allDataIsLoadedfalse

当我设置timeout时:一切都像魅力一样工作。但我不认为这是一个好的解决方案。如何在不超时的情况下延迟我的函数?

在异步函数中使用超时不是一个好主意:

  1. 如果您的请求时间较长,则超时,则会收到不必要的请求。

  2. 如果您的超时比请求时间更大,那么您将获得不必要的滞后。

您应该对请求使用承诺链。尝试这样的事情:

var asyncService = function ($timeout)
    {
        var someData = 10;
        var service =
            {
                FetchData: function (someArray)
                {
                    someData++;
                    //timeout here is just for demonstration of async request
                    return $timeout(function () { return someData }, 1000)
                        .then(function (result)
                        {
                            return service.ProcessData(result, someArray);
                        });
                },
                ProcessData: function (data, someArray)
                {
                    console.log(data);
                    if (data == 15)
                    {
                        return someArray;
                    }
                    else
                    {
                        someArray.push(data)
                        return service.FetchData(someArray);
                    }
                }
            };
        return service;
    }

这是一个带有演示的 plunker