1

I have the next code:

$.get('Lubricantes/getListaEquipos', function (data) {
        if (data.length > 0) {
            var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').clear();

            total_equipos = data.length;

            peticion.onerror = function () {
                console.log('No se pudo limpiar el maestro de equipos.');
            };
            peticion.onsuccess = function (e) {
                for (var i = 0; i < data.length; i++) {
                    var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').add(data[i]);
                    peticion.onerror = function (e) {
                        console.log('No se pudo cargar el equipo' + i);
                    };
                    peticion.onsuccess = function (e) {
                        console.log('Equipo ' + i + ' agregado');
                    };
                }
            };                                
        }
    });

When this execute the var i don't exist, how can pass to add method the value of i?

1 Answers1

2

Async is fun, isn't it?

I'll save you the lecture on scopes and variable references and just recommend that you just wrap the guts of your for loop into an "immediately invoked anonymous function" like so:

    $.get('Lubricantes/getListaEquipos', function (data) {
        if (data.length > 0) {
            var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').clear();

            total_equipos = data.length;

            peticion.onerror = function () {
                console.log('No se pudo limpiar el maestro de equipos.');
            };
            peticion.onsuccess = function (e) {
                for (var i = 0; i < data.length; i++) {
                    (function(entrada, j) {
                        var peticion = base_datos_local.transaction(['Equipos'], 'readwrite').objectStore('Equipos').add(entrada);
                        peticion.onerror = function (e) {
                            console.log('No se pudo cargar el equipo' + j);
                        };
                        peticion.onsuccess = function (e) {
                            console.log('Equipo ' + j + ' agregado');
                        };
                    })(data[i], i);
                }
            };                                
        }
    });

data[i] is evaluated immediately and passed in as an argument to this closure, so you'll have the correct reference in scope when the callbacks eventually fire.

buley
  • 28,032
  • 17
  • 85
  • 106