Search code examples
ajaxangularjsangular-promiseangular-resource

Ajax call within a loop using $resource


I'm in difficulty doing this operation correctly.

I have an Order and for every item I have to get the data from the API, what I'm doing is this:

if ($scope.order.order_items.length > 0) {
    var itemArray = [];
    for (var i = 0; i < $scope.order.order_items.length; i++) {
      var itemId = $scope.order.order_items[i].id;
      Items.get({
        itemId: itemId
      }).$promise.then(function (data) {
        itemArray.push(data.item);
      });
    }
    $scope.order.order_items = itemArray;
  }

The API receive the request and send the data back but the promise do not return anything...

One more error here is from jshint: Don't make functions within a loop.

It will be nice to solve both the issues for me... I tried to create an external function but having the same issue not returning data I don't know if I was doing it well, the external function I was doing is:

function addItem(id) {
    Items.get({
      itemId: id
    }).$promise.then(function (data) {
      console.log(data);
      return data.item;
    });
  }

Solution

  • You are making an asynchronous call from the code and thinking that it will work like synchronously. As you are assigning itemArray to $scope.order.order_items outside the factory, at that time itemArray is blank. Before making that assignment you need to ensure that all the ajax call the each item has been completed or not. You could use $q.all for such scenario. $q.all need an promise array & it will call the .then function when all the promise gets resolved.

    if ($scope.order.order_items.length > 0) {
        var itemArray = [], promiseArray = [];
        for (var i = 0; i < $scope.order.order_items.length; i++) {
          var itemId = $scope.order.order_items[i].id;
          var currentPromise = Items.get({
            itemId: itemId
          }).$promise.then(function (data) {
             itemArray.push(data.item);
             return true; //returning dummy value from promise.
          });
          promiseArray.push(currentPromise); //creating promise array
        }
        $q.all(promiseArray) //giving promise array input.
        .then(function(data){ //success will call when all promises get resolved.
            $scope.order.order_items = itemArray;
        },function(error){
            console.log("Error occured")
        });
    
    }