How to pass parameters to mysql query callback in nodejs

前端 未结 3 1248
余生分开走
余生分开走 2020-11-30 12:37

I\'m trying to figure out the correct way of passing custom data to a query call to be made available in the callback. I\'m using MySQL library in nodejs (all latest version

3条回答
  •  一个人的身影
    2020-11-30 12:52

    While it is OK to pass variables or objects to a mysql query callback function using the tactic described earlier -- wrapping the callback function in an anonymous function -- I think it is largely unnecessary, and I'll explain why with an example:

    // This actually works as expected!
    
    function run_query (sql, y) {
        var y1 = 1;
        connection.query (sql, function (error, rows, fields) {
    
            if (! error)
            {
                var r = rows[0];
    
                console.log ("r = " + r[1]);
                console.log ("x = " + x);
                console.log ("y = " + y);
                console.log ("y1= " + y);
                console.log ("");
            }
            else
            {
                console.log ("error = " + error);
            }
        });
    };
    
    var x = 5;
    
    console.log ("step 1: x = " + x);
    
    run_query ("SELECT 1", x);
    
    x = x + 1;
    
    console.log ("step 2: x = " + x);
    
    run_query ("SELECT 1", x);
    
    x = x + 1;
    
    console.log ("step 3: x = " + x);
    

    Produces the following output:

    step 1: x = 5
    step 2: x = 6
    step 3: x = 7
    r = 1
    x = 7
    y = 5
    y1= 5
    
    r = 1
    x = 7
    y = 6
    y1= 6
    

    The fear is that the second call to run_query() will overwrite the variable y and/or y1 before the first call to run_query() has a chance to invoke its callback function. However, the variables in each instance of the called run_query() function are actually isolated from each other, saving the day.

提交回复
热议问题