Nodejs asynchronous programming variable transfer problem.

  node.js, question
for(var i = 0;   i < res.length;  I plus)
 
 var info = res[i];
 Var fpath = attach_root_dir plus'/'plus picker_id plus'/'plus article_data._id plus'/'plus info.fileName;
 
 dlog(fpath);  //Position 1
 
 nodeRequire('fs').exists(fpath, function (exists) {
 
 dlog(fpath);  //Position 2
 });
 bracket

This code is not posted completely.
The general function is to read the attachment list circularly from the database, and then judge whether the file of this attachment exists or not according to the information and path of each attachment.

The problem now is that the fpath variable obtained at position 2 is always the same.
In other words, the fpath of the outer layer cannot be correctly transferred to position 2. Because of asynchronous execution. How to solve this problem?

Reason

You didn’t ask why, but I’d better explain why.

The fpath variable is only a variable (reference), and the callback function you pass only knows: “oh, I can get (reference) the value of fpath then.”

The key lies in that when you transfer a function, you are only transferring an unexecuted function. The function inside has a variable fpath, and because it has not been executed, you have not obtained the current value.

By the time asynchronous functions are to be acquired, the value of fpath is already the last.

solution

Suppose the problem is:

var a = [1,2,3,4,5,6,8]
 
 for (var i = 0;   i < a.length;  I plus)
 var c = a[i]
 setTimeout(function(){
 console.info(c);
 }, 100)
 bracket

Solution 1: (Original Solution)
The solution is also very simple. It was said above that the function was not executed at that time. We can create a function to execute a part and save it with another variable (of the new function).

var a = [1,2,3,4,5,6,8]
 
 for (var i = 0;   i < a.length;  I plus)
 var c = a[i]
 ;  (function(c){
 setTimeout(function(){
 console.info(c);
 }, 100)
 })(c)
 bracket

Solution 2: (es6 Solution)

var a = [1,2,3,4,5,6,8]
 
 for (var i = 0;   i < a.length;  I plus)
 let c = a[i]
 setTimeout(function(){
 console.info(c);
 }, 100)
 bracket