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


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:'mysubdata')
.then(function(data) {
   var dataList = data;
   for (returnedData in dataList) {'mysubdata','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.


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;'mysubdata')
  .then(function (data){
     dataList = data;
     myCustomData = mydata;

$scope.getSubSubData = function () {
   if (dataList.length >= dataListCounter)
     .then(function (returnedSubData) {
        dataList = angular.extend(dataList, returnedSubData);

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.