3
I wonder if I have how to pass some external value into the asynchronous function keeping the value of when the function was called.
for(x=0;x<array.length;x++){
fs.readfile(path,function(error,file){
console.log(file.data == array[x]);
});
}
When I run the reading of the file inside the loop the asynchronous function always fires after the loop finishes the execution, not getting the value of when the reading started.
To resolve this I ended up calling the read file synchronously
for(x=0;x<array.length;x++){
file = fs.readfileSync(path);
console.log(file.data == array[x]);
}
But I do not know if it is the best solution, and I wonder if there is a way to pass the value of X into the asynchronous function because not all functions will have a synchronous alternative as is the case of readFile
.
Use
let x = 0
instead ofx = 0
– Costamilam