Q:

how to create functional/method loop javascript

i have an app the automatically insert data to mongodb after calling an api in jive, my problem is the response is paginated. 
var getAPICall=function(apiLink){
  console.log(apiLink);
  var response = HTTP.get(apiLink, {
             headers: {
                 Authorization: getAPIToken()
             }
    });
  return response;
}

var getAPIToken = function(){
  var token = HTTP.post("https://api.jivesoftware.com/analytics/v1/auth/login?clientId=fakeclientid.i&clientSecret=fakesecret.s");
  //console.log(token);
  return token.content;
}

the response looks like this. 
{"paging":{"next":"https://cloudalytics-api-phx.prod.jivehosted.com:443/analytics/v2/export/activity/lastday?startIndex=100&count=100&show-all=true","itemsPerPage":100,"totalCount":164406,"currentPage":1,"totalPages":1645}, list: [{....}]}

which has next, currentPage and totalPage field
im planning to do a loop for the next page function and stop when totalPage is equal to currentPage
im doing this
var res = getAPICall(baseline);    
_.each(res.data.list, function(item) {
    console.log(item.uuid);
    Reports.upsert({"uuid":item.uuid},{$set :item});
    });

var totalPage = res.data.paging.totalPage; 
for(var current = res.data.paging.currentPage ;  current <= totalPage ;) {
    var res = getAPICall(res.data.paging.next );    
        _.each(res.data.list, function(item) {
            console.log(item.uuid);
            Reports.upsert({"uuid":item.uuid},{$set :item});
            });
}

but this statement only runs until the next page with infinite loop. any ways i can do this better with functional approach? 
im new in javascript please hammer me.
thanks!

A:

this should be pretty simple with recursion.
var myFunction = function(baseline){
  var res = getAPICall(baseline);
  _.each(res.data.list, function(item) {
    console.log(item.uuid);
    Reports.upsert({"uuid":item.uuid},{$set :item});
  });
  if (res.data.paging.currentPage != res.data.paging.totalPage) {
    myFunction(res.data.paging.next)
  }
}    

myFunction(baseline);

