Node: Tips for Asynchronous Development

Node: Tips for Asynchronous Development

Use anonymous functions to save global variables

Take a look at a piece of code:

function asyncFunction(callback){
    
    
    setTimeout(callback,200);
}
let color = 'blue';
asyncFunction(()=>{
    
    
    console.log(`The color is ${
      
      color}`);
})
color = 'green';

I believe everyone knows that the output of the above code must be: The color is green.

Because this example is asynchronous, the color has been re-assigned to'green' before the console.log is executed, so the result is not in line with expectations.

In order to solve this problem, you can use JavaScript closures to save global variables

function asyncFunction(callback){
    
    
    setTimeout(callback,200);
}

let color = 'blue';
(color=>{
    
    
    asyncFunction(()=>{
    
    
        console.log('The color is',color );
    });
})(color);

color = 'green';

After using the closure, the color becomes a local variable in the closure, and will not be affected by the change of the variable outside the closure.

Guess you like

Origin blog.csdn.net/yivisir/article/details/107831076