$ http请求在单个请求中返回所有没有分页的记录

时间:2016-04-06 17:07:02

标签: javascript angularjs recursion angular-promise

有超过4000条记录。 API返回最多1000条记录并具有分页功能。我呼吁这个函数(循环),并使用" skip"以1000个记录的间隔获取记录。

我一次需要所有记录,但是下面的代码只返回前1000条记录。

  var array=[];
  function loop(skip){
     return $http({
            method: 'GET',
            url: myurl+'&$skip='+skip,
            timeout:5000
      }).success(function(res){
        if(res.d.length>0) 
            {
              Array.prototype.push.apply( array,res.d);
               loop(skip +1000);
            }
        return array;
      }).error(function(response,status,headers,config) {

      });
    }

    getAll = function() {
        return loop(0);
    }

我需要单个请求才能获得总记录。 但只有我得到这一部分的前1000条记录:(

    getAll().then(function() {
        console.log("in this part i need the array with my 4000 records")
    });

3 个答案:

答案 0 :(得分:2)

应该可以通过一些递归承诺链接。试试这个

function getAll(page) {
    if (typeof page === 'undefined') {
        page = 0;
    }
    return $http.get(myurl, {$skip: page * 1000}).then(function(res) {
        var data = res.data;
        if (data.length > 0) {
            return getAll(page + 1).then(function(nextData) {
               return data.concat(nextData);
            });
        }
        return data;
    });
}

并称之为

getAll().then(function(allRecords) {
    console.log(allRecords);
});

这是一个被黑客攻击的示例〜http://plnkr.co/edit/ey8gdytvuBE6cpuMAtnB?p=preview

答案 1 :(得分:2)

首先,来自角doc的一点注释:

  

已弃用$http遗留承诺方法successerror。请改用标准方法。如果$httpProvider.useLegacyPromiseExtensions设置为false,则这些方法会抛出$http/legacy错误。

又一个解决方案:将累加器结果作为参数传递给循环函数

function loop(skip,result){
  result = result||[];//accumulator for result, init empty array if not pass
  return $http(
    {
          method: 'GET',
          url: myurl+'&$skip='+skip,
          timeout:5000
    }).then(function success(response){
      if(response.data.length > 0){
        Array.prototype.push.apply(result,response.data);
        return loop(skip+1000,result);
      }
      return result;
    },function error(){

    });
}

请注意,在成功处理程序中调用return函数之前,与当前代码的主要区别是loop

这项工作,因为如果来自then函数返回承诺,则在返回的承诺完成后将应用下一个then

<强> Sample plunkr

答案 2 :(得分:0)

在 工作样本https://jsfiddle.net/coolbhes/xmqur1bq/(用承诺替换服务)

适用于您的代码如下:

var array = [];

function loop(skip, resolveHandle) {
    $http({
        method: 'GET',
        url: myurl + '&$skip=' + skip,
        timeout: 5000
    }).then(function successCallback(res) {
        if (res.d.length > 0) {
            Array.prototype.push.apply(array, res.d);
            loop(skip + 1000, resolveHandle);
        } else {
            //done with all requests;
            resolveHandle(array);
        }
    }, function errorCallback(rej) {

    });
};

function getAll() {
    return new Promise(function(resolve, reject) {
        loop(0, resolve);
    });
}

getAll().then(function(data) {
            console.log("in this part i need the array with my 4000 records", data)
        }