是否可以将数组传递到mysql回调函数中,如:

connection.query('SELECT count(id) as wynik FROM used where asset_id =
  \''+asid+'\'', inventory[i],function(err,wiersze){
    console.log(inventory[i]);
});

现在inventory[i]在里面不可用,但我需要它。

最佳答案

因为您在for循环中,所以需要使用立即调用的匿名函数或简单的.forEach()。这两个都是下面的例子。
立即调用匿名函数

for (var i = 0; i < inventory.length; i++) {
    (function(i) {
        if (inventory[i].market_hash_name == rows[j].real_name) {
            var asid = inventory[i].assetid;
            connection.query('SELECT count(id) as wynik FROM used where asset_id = \'' + asid + '\'', function(err, wiersze) {
                console.log(inventory[i]);
                process.exit(1);
                if (wiersze[0].wynik == 0) {
                    var employee = {
                        asset_id: asid,
                        trans_id: rows[j].tid
                    };
                    connection.query('INSERT INTO used SET ?', employee, function(err, res) {
                        if (err) throw err;
                        offer.addMyItem(inventory[i]);
                    });
                    licznik++;
                }

            });

        }
    })(i);
});

.forEach()
inventory.forEach(function(item) {
    if (item.market_hash_name == rows[j].real_name) {
        var asid = item.assetid;
        connection.query('SELECT count(id) as wynik FROM used where asset_id = \'' + asid + '\'', function(err, wiersze) {
            console.log(item);
            process.exit(1);
            if (wiersze[0].wynik == 0) {
                var employee = {
                    asset_id: asid,
                    trans_id: rows[j].tid
                };
                connection.query('INSERT INTO used SET ?', employee, function(err, res) {
                    if (err) throw err;
                    offer.addMyItem(item);
                });
                licznik++;
            }

        });

    }
});

10-04 22:48