How do I use a function inside a loop inside a .then?

Issue

I have an Angularjs project that uses Restangular to access the database. I have three layers of data (say mydata, mysubdata, mysubsubdata) and there is a one-to-many relationship between each layer. My problem is that, for my display, I need to concatenate the mysubsubdata to the mysubdata. When I try to get data back from the database, I am hitting a complaint in the compiler that says I can’t have a function in a loop. Here is what I am trying to do:

DataService.one(mydata.id).getList('mysubdata')
.then(function(data) {
   var dataList = data;
   for (returnedData in dataList) {
     DataService.one(mydata.id).one('mysubdata',returnedData.id).getList('mysubsubdata')
    .then(returnedSubData) {
       dataList = angular.extend(dataList, returnedSubData);
    });
  }
});

All the examples I’ve found have loops inside the .then function or are trying to get a bunch of promises back first. I don’t think those apply. I’m still pretty new to Angular, so I may be flailing a bit. Not sure about the extend either, but that’s likely a separate question.

Edit: I suspect this should be done with a $q.all but haven’t grasped the method yet.

Solution

Adding a then() method inside your loop won’t work because of the simple reason that loop does not wait for the promises to be resolved. You can achieve this using recursive method.

var myCustomData = null,
    dataList = null,
    dataListCounter = 0;

DataService.one(mydata.id).getList('mysubdata')
  .then(function (data){
     dataList = data;
     myCustomData = mydata;
     $scope.getSubSubData();
});

$scope.getSubSubData = function () {
   if (dataList.length >= dataListCounter)
     return;
   DataService.one(myCustomData.id).one('mysubdata',dataList[dataListCounter].id).getList('mysubsubdata')
     .then(function (returnedSubData) {
        dataList = angular.extend(dataList, returnedSubData);
        dataListCounter++;
        $scope.getSubSubData();
   });
};

Please let me know if this helps!

Answered By – Anadi Sharma

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.