In the following examples, asynchronous operations are shown, inside loops.
The primer ejemplo
does not work and is an expected result as the loop terminates execution and the callbacks return the last value of the variable looped through.
He segundo ejemplo
solves the above with the use ofbind.
He tercer ejemplo
creates an anonymous function that executes itself and is passed the correct value. This new function creates a new scope and the function called within it contains the correct value for each iteration.
He último ejemplo
uses a loop forEach
, which produces a correct result since the value of each iteration is encapsulated in a function, creating a new scope...
var obj = {
key : 'val',
key2 : 'val'
};
function funcionAsync(cb){
setTimeout(cb, 1000);
}
// Quiero evitar hacer esto, es decir, ir pasando el parámetro entre funciones
function funcionAsyncConParam(param, cb){
setTimeout(()=>cb(param), 1000);
}
var keys = Object.keys(obj);
//NO funciona, imprime key2 key2
for(k of keys){
funcionAsync(function(){
console.log(k, 'Función 1');
});
}
//Funciona, imprime key key2 (Pero se quiere evitar)
for(k of keys){
funcionAsyncConParam(k, function(k){
console.log(k, 'Función EVITAR');
});
}
//Funciona, imprime key key2
for(k of keys){
funcionAsync(function(k){
console.log(k, 'Función 2');
}.bind(null, k));
}
//Funciona, imprime key key2
for(k of keys){
(function(k){
funcionAsync(function(){
console.log(k, 'Función 3');
});
})(k);
}
// Funciona, imprime key key2
keys.forEach(function(k){
funcionAsync(function(){
console.log(k, 'Función 4');
});
});
I think I understand why the various solutions work, my question is: Is there any other way to pass the current value of the loop as a reference to an asynchronous function or event handler?
I think you are not iterating your object correctly, here I am going to leave you how to iterate the
object
, I hope it works for what you are looking for.continuation edition
In this code, I pass an anonymous function and it runs after 3 seconds.
edit by comment I made a screenshot of the result that the console shows me