2015-10-07 72 views
0

我正在構建帶有節點js和net-snmp模塊的linux服務器監視。這部分是腳本來檢查存儲在mysql數據庫上的OID。我得到了問題,這個腳本總是隻執行最新的循環。我不知道爲什麼。這裏是我的代碼:使用循環但始終執行最新循環 - node.js net-snmp

connection.query("select * from SERVICE WHERE SERVER_ID = ? order by SERVICE_LIST_ID", [result[i].SERVER_ID], function(err2, services) { 
    if (err2) throw(err2); 

    //tapping services 
    for(var j in services){ 
     session.get ([services[j].SERVICE_OID], function (error, varbinds) { 
      if (error) { 
       console.error (error); 
      } else { 
      //save services 
      console.log(j); 
      var post = {LOG_ID: result_logr.insertId, SERVICE_ID: services[j].SERVICE_ID, SERVICE_STATUS: 1}; 
      var query = connection.query('INSERT INTO LOG_SERVICE SET ?', post, function(err, result) { 
        if (err) { 
       connection.rollback(function() { 
        throw err; 
       }); 
       } 
       connection.commit(function(err) { 
       if (err) { 
        connection.rollback(function() { 
        throw err; 
        }); 
       } 
       console.log('Transaction Complete.'); 
       //connection.end(); 
       }); 
       }); 
       console.log(query.sql); 
      } 

     }); 
    } 
    }); 

而結果的顯示:

1 
INSERT INTO LOG_SERVICE SET `LOG_ID` = 115, `SERVICE_ID` = 2, `SERVICE_STATUS` = 1 
1 
INSERT INTO LOG_SERVICE SET `LOG_ID` = 115, `SERVICE_ID` = 2, `SERVICE_STATUS` = 1 

因此,它只能執行J = 1。 請幫幫我。謝謝

回答

0

也許異步的問題,將執行平穩。

嘗試此:

async = require('async') 
async.eachSeries(services, function(elem,callback){ 
//Your logic here 

AFter that 
callback(); //to start the next loop 
})