How to use a counter value within asynchronous function

Asked

Viewed 39 times

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.

  • 2

    Use let x = 0 instead of x = 0

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.