I'm starting with Javascript and I still don't handle the asynchronous theme well, promises... etc
The issue is that within a callback I need to access the data of an array (go through it using a for) and this throws me an error that I don't 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 have shortened the code a bit, to make the example simpler. The content of dataLayer is an array of objects and I want to keep the label attribute of each one.
The error it 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: {}
Your problem is the condition of the for loop:
is equivalent to writing
since
dataLayer.length
is 1, always calculatestrue
. What you need is to compare the length with your index:By the way, naming callback functions is a good practice because it helps debug errors, as you've seen it appear in the "stacktrace" of the error message.