Error with promise and cycle for

1

I'm starting with Javascript and I still do not handle the asynchronous topic well, promises ... etc

The question is, that within a callback I need to access the data of an array (traverse it through a for) and this throws me an error that I do not know how to fix.

My code:

var objetoQueGuardo = {'event': 'evento1', 'label': 'valor'};
var dataLayer = [];
dataLayer.push(objetoQueGuardo);

factura.createFactura(id, false, token)
                .then(function successCallback(response) {

            for (var i = 0; dataLayer.length; i++) {
                dataLayer[i].label;
            }

}, function errorCallback(response) {
                    console.warn(response);
});

I shortened the code a bit, so that example is simpler. The content of dataLayer is an array of objects and I want to keep the label attribute of each one.

The error that shows me:

 TypeError: dataLayer[i] is undefined
 Traza de la pila:
    successCallback@http://api.local/components/api/assets/js/factura.js:150:7
    h/<@http://api.local/components/api/assets/bower_components/angular/angular.min.js:135:278
    $digest@http://api.local/components/api/assets/bower_components/angular/angular.min.js:146:238
    $apply@http://api.local/components/api/assets/bower_components/angular/angular.min.js:149:464

 Possibly unhandled rejection: {}
    
asked by Norak 31.08.2017 в 13:47
source

1 answer

3

Your problem is the condition of the for loop:

for (var i = 0; dataLayer.length; i++) {
    dataLayer[i].label; // En este ejemplo esta sentencia realmente no hace nada, pero sirve para detectar el error
}

is equivalent to writing

for (var i = 0; !!(dataLayer.length); i++) { // !!1 === true
    dataLayer[i].label;
}

since dataLayer.length is 1, true is always calculated. What you need is to compare the length with your index:

for (var i = 0; i < dataLayer.length; i++) {
    dataLayer[i].label;
}

By the way, naming the callback functions is a good practice because it helps to debug errors, as you have seen it appears in the "stacktrace" of the error message.

    
answered by 31.08.2017 / 14:33
source