Object does not exist when a foreach is inside another except during debugging

4

In my code I consulted 2 services and put their results (objects) within an array called deferreds .

These objects have a property called results , which is another array .

I need to get the first of these objects, and give a push() of all results of the other objects in it, because I'm going to display it in a popup .

My problem is that this only works when I put a breakpoint in the browser and I go from line to line. When I run normal in the browser, it gives an error saying def.results[0] is undefined, but when I go slowly debugando it does have a value, and everything runs normal.

Any tips?

var deferred = null;
deferreds.forEach(function (def) {
    if (deferred == null) {
        deferred = def;
    } else {

        def.results[0].forEach(function (defer) {
            deferred.results[0].push(defer);
        });
    }
});


this.mapa.infoWindow.setFeatures([deferred]);
this.mapa.infoWindow.show(evt.mapPoint);
    
asked by anonymous 11.10.2016 / 19:32

2 answers

0

Thanks everyone, I think the problem was that the deferred was not even ready. (Think). I solved using% DO of the DOJO framework like this:

var deferred = deferreds[0];

var teste;

for (var i = 1, max = deferreds.length; i < max; i++) {
    when(deferreds[i], function (results) { teste = results; });

    when(deferred, function (results) {

        teste.forEach(function (item) {
            results.push(item);
        });
    });
}

this.mapa.infoWindow.setFeatures([deferred]);
this.mapa.infoWindow.show(evt.mapPoint);
    
11.10.2016 / 21:40
0

Oops, blz? Dude, if your goal is to put all the results in the first object of your array, it would not be better for you to do this:

var first = null;
if(deferreds.length > 1) {
  first = deferreds.shift()
  deferreds.forEach(function (item) {
    first.result = first.result.concat(item.result);
  });    
} else {
  first = deferreds[0]
}

first.result
    
11.10.2016 / 20:32