angularjs synchronous

0

I have the following driver.js:

var result = [];
var d = ["MS_SNA_CONTROL_TAB","MS_SNA_EXT_LOSS_TAB"];

for(var i = 0; i < d.length; i++){ 
  var filter = {};
  filter.name = d[i];

  EOGService.query(queryP).then(
    function(a) {
            filter.results = a;
            console.log("añade : " + d[i])
            results.push(filter);
        }
  ); 

  console.log("ha terminado: " + results);
}

My problem is that the order of the console is:

ha terminado: undefined
añade MS_SNA_CONTROL_TAB
añade MS_SNA_EXT_LOSS_TAB

And I need it to be

añade MS_SNA_CONTROL_TAB
añade MS_SNA_EXT_LOSS_TAB
ha terminado: object

Thanks

    
asked by sirdaiz 04.01.2017 в 14:23
source

3 answers

2

In fact, the way you are creating the promises you will never manage to control when they end. For this you must convert your array of values into an arrangement of promises and use $q.all to control when all have ended.

Something like this

var promises = [];
var result;
var d = ["MS_SNA_CONTROL_TAB","MS_SNA_EXT_LOSS_TAB"];

for(var i = 0; i < d.length; i++) { 
    var promise = EOGService.query(queryP);
    promises.push(promise);
}

$q.all(promises).then(function(results) {
    results.forEach(function(a, index) {
        var filter = {};
        filter.name = d[index];
        filter.results = a;
        console.log("añade : " + d[index]);
        results.push(filter);
    });

    console.log("ha terminado: " + results);
}); 

}

    
answered by 04.01.2017 / 14:45
source
0

The problem is in the way you conceive the operation of angular, with respect to the EOGService service that you are using that is asynchronous, in this case the function really ends where it does the push, and supposing that it is a function it would take a promise or a callback to return the result something like that

function funcAsincronica(callback){
      var result = [];
      var d = ["MS_SNA_CONTROL_TAB","MS_SNA_EXT_LOSS_TAB"];
      for(var i = 0; i < d.length; i++){ 
      var filter = {};
      filter.name = d[i];
      EOGService.query(queryP).then(
      function(a) {
              filter.results = a;
              console.log("añade : " + d[i])
              results.push(filter);
               if(result.length == d.length){
                  callback(result);
               }
       }); 
 }

  funcAsincronica(function(result){
         console.log("ha terminado: " + results);
  });
    
answered by 04.01.2017 в 14:44
0

So you should do what you want without having to do it synchronously

var result = [];
var d = ["MS_SNA_CONTROL_TAB","MS_SNA_EXT_LOSS_TAB"];

for(var i = 0; i < d.length; i++){ 
  var filter = {};
  filter.name = d[i];

  EOGService.query(queryP).then(
    function(a) {
            filter.results = a;
            console.log("añade : " + d[i])
            results.push(filter);
 console.log("ha terminado: " + results);
        }
  ); 

 
}
    
answered by 04.01.2017 в 14:45