Tuesday, 30 May 2017

Mutable Variable is in accessible from closures

I'm new to javascript. Here is my code

  ......
var filename, result, user=["a", "b", "c","d"];
for(var p=0;p<user.length;p++)
      {
       filename=userID[p]+'_'+user[p]+'.json';

       fs.readFile(filename, function read(err, data)
       {
           if (err) {throw err;}
           result = data.toString();

            if (result.charAt(result.length-1) === ',')
             result = result.substring(0,result.length-1) + ']}';

          console.log(p+filename+result+"\n\n"); //here

            });

         }

In "here" the value of p is always showing the last index, in this case 3 in for all iterations also the filename is the for the last iteration.How can I get the correct value of p in "here". For p my compiler shows "Mutable Variable is in accessible from closures".



via ARUNIMA

No comments:

Post a Comment