2

I'm trying to create an object by forEach on the responses of various services .. and I do not get the results I need. I know I should use internal iterations promises but do not know how yet ..

EDIT:

well .. I need is to do is to fill an object of the data into $ foreach foreach .. http into a iteration promises, sample code:

someservice1.getitem().then(function(){
   var dataInfo= {};
      angular.foreach(data, function(v, k){

         dataInfo[v]=[]
         someservice2.getitem2(k.data).then(function(data){

               datainfo[v].push(data)

         })
     })
$scope.dataInfo = datainfo;
})

so not working very well .. I think you can solve by using promises but I could not do it. I hope your help

7
  • Welcome to SE. Unfortunately, as it stands, you question is not at a standard where anyone would answer it. Firstly I do not speak Italian, so I have no idea what your code says, secondly I am not paid enough (free) to read all your code to figure out your problem. Please could you try to condense down your problem into as few lines as possible so that we can quickly answer your question.
    – Aron
    Jan 13, 2016 at 3:14
  • @franco, where does this actividades in actividades.listar() variable come from...
    – mido
    Jan 13, 2016 at 3:23
  • Shouldn't the first line be someservice1.getitem().then(function(data){??
    – georgeawg
    Jan 13, 2016 at 5:22
  • @mido Your edit switched value and key in the forEach. It should be angular.foreach(data, function(v,k). The first argument of the iteration function should be the value; the second argument, the key.
    – georgeawg
    Jan 13, 2016 at 7:49
  • @georgeawg i just copy pasted franco's answer, updated now :)
    – mido
    Jan 13, 2016 at 7:52

2 Answers 2

2

The problem is that the final $scope.dataInfo = datainfo; is executing early before the datainfo object gets completed. You need to create a promise from which that operation can chain safely.

finalPromise.then ( function (datainfo) {
    $scope.dataInfo = datainfo;
});

You create finalPromise by returning and chaining from previous promises.

var service1Promise = 
    someservice1.getitem().then(function(data){
        var promiseList = [];
        angular.foreach(data, function(v,k){
            var p = someservice2.getitem2(k.data);

            p.then(function(data) {
                 //return key and data for chaining
                 return { key: k, data: data };
            }) .catch (function (error) {
                 //throw key and error to chain rejection
                 throw { key: k,  error: error };
            });
            //push to list
            promiseList.push(p);
         });
         //return $q.all promise for chaining
         return $q.all(promiseList);
});

Create finalPromise by chaining from service1Promise

var finalPromise = 
    service1Promise.then(function(fulfilledList) {
        var dataInfoObj = {};
        //assemble data info
        angular.forEach(fulfilledList, function (fulfilledItem) {
            dataInfoObj[fulfilledItem.key] = fulfilledItem.data;
        });
        //return datainfoObj for chaining
        return datainfoObj;
});

Now you can chain from the finalPromise to put the data on $scope

finalPromise.then ( function onFulfulled (datainfo) {
    $scope.dataInfo = datainfo;
}).catch (function onRejection (error) {
    console.log("finalPromise rejected");
    console.log(error.key);
    console.log(error.error);
});

Be aware that $q.all is not resilient. If any of the promises are rejected, $q.all will be rejected with the first rejection.

For more information on chaining promises see the AngularJS $q Service API Reference -- chaining promises.

1

You are using angularjs, so with $q, for array of promises within promises you could make your code into something like this:

// first add $q service to your controller, 

someservice1.getitem()
  .then(function(data){
    var dataInfo= {};
    var promises = angular.map(data, function(item, index){
      var promises2 = angular.map(item.data, function(iData){
        someservice2.getitem2(iData)
      })
      return $q.all(promises2).then(function(resultArray){
        dataInfo[index] = resultArray;
      });
    });
    return $q.all(promises).then(function(){
      console.log('all data are retrived...');
      $scope.dataInfo = datainfo;
    });
  });

the same might look more elegant in ES6:

let serviceCall2 = data => someservice2.getitem2(data);  // serviceCall2 is just a closure for someservice2.getitem2() call
someservice1.getitem()
  .then(data => {
    let dataInfo= {}, 
      promises = data.map((item, index) => {
        let promises2 = item.data.map(serviceCall2);
        return $q.all(promises2).then(resultArray => dataInfo[index] = resultArray);
      });
    return $q.all(promises)
      .then(() => {
        console.log('all data are retrived...');
        $scope.dataInfo = datainfo;
      });
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.