节点循环中的选择和插入不按预期工作

时间:2017-08-05 09:16:44

标签: mysql node.js express

我正在尝试在检查数据库表中是否已存在之前在表中插入数据?如果存在则循环继续控制台消息“已经存在”并且如果不存在则我尝试在表中插入。但有些记录已经在数据库表中,然后也插入表中。

关注我的NodeJS代码

(function loop(index){
            if(index==apires.items.length){     
                console.log("Cron completed");              
                res.send("Cron completed");
                return false;
            }
            inventoryObj = apires.items[index];
            hash_name = inventoryObj.market_hash_name;

            db.query('SELECT market_hash_name FROM inventory_master WHERE market_hash_name = "'+hash_name+'"', function(err,result, fields){
                if(result.length){
                    console.log('already exist');
                    loop(++index);
                }
                else
                {
                    var post  = {data_here};
                    var query = db.query('INSERT INTO inventory_master SET ?', post, function (error, results, fields) {
                    if (error) throw error;           
                        loop(++index);
                    });
                }   
            });     
        })(0);

1 个答案:

答案 0 :(得分:1)

我想这是由于代码的异步行为而发生的。您可以使用async库使其工作,这将允许您的代码一次在元素上执行。示例

// assuming apires.itemsis an array 
async.each(apires.items, function(inventoryObj, callback) {

            hash_name = inventoryObj.market_hash_name;

            db.query('SELECT market_hash_name FROM inventory_master WHERE market_hash_name = "'+hash_name+'"', function(err,result, fields){
                if(result.length){
                    console.log('already exist');
                    callback('success'); // go for next iteration
                }
                else
                {
                    var post  = {data_here};
                    var query = db.query('INSERT INTO inventory_master SET ?', post, function (error, results, fields) {
                    if (error) throw error;           
                        callback('success'); // go for next iteration
                    });
                }   
            });     
}, function(err) {
   //once all finished, it will come here,if no error occurred then err will be null
});