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

Asked

Viewed 119 times

4

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

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

I need to take the first of these objects, and give one push() of all the results of the other objects in it, for I will display it in a popup.

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

Any hint?

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);
  • making def.Results[0]. foreach you are not traversing the array, you are only accessing the value, which alone cannot be traversed. removes this [0] ai that will work :D from a console.log() ae and takes the object

  • What gives console.log(JSON.stringify(deferreds));? You can enter the code of the two services you consult?

  • I think you’re trying to access the results before the deferred has been resolved.

  • Thanks @Gabrielrodrigues, is that inside the Results there was an array. The first position with the objects I mentioned, and another empty. That’s why I put [0].

  • Thanks @bfavaretto. I’m not sure but I think the problem was that. I managed to solve using the when of the DOJO Framework I’m using, to access the property of each results

  • Thanks @Sergio, I think the problem was that the deferred was not ready at all. Already put as I solved

Show 1 more comment

2 answers

0

Whoa, whoa, blz, whoa? Dude, if your goal is to put all the Results in the first object of your array, wouldn’t it be better to do so:

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

0


Thanks guys, I think the problem was that the deferred was not ready at all. (I think). I decided using the When of the DOJO framework so:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.