2015-12-14 134 views
0

我對java腳本和節點js很陌生。 我有一個簡單的函數,我打電話的問題,它不止一次完成。 這是我的代碼同步節點js功能

app.post('/checkGetSensorIds', function (req, res) { 
    var tables=['temperature', 'pressure', 'linear_acceleration']; 
    var ids= [1]; 
    DButils.checkAllSensorsForId(connection, 1 , tables , function(idHasSensorsInfo){ 
    console.log("idHasSensorsInfo is: \n" , idHasSensorsInfo); 
    }); 
    res.end(); 
}); 


/*this function gets a user Id, and the table of all sensors the customer wants, and return true if this 
user id has information in all the sesnsor tables that were requested, otherwise returns false*/ 
exports.checkAllSensorsForId= function(dbConnection, id , sensorsTables, callback){ 
    var sensorsTablesLength= sensorsTables.length; 
    for (var i = 0; i < sensorsTables.length; i++) { 
     var tableName= sensorsTables[i]; 
     DButils.checkSingleSensorForId(dbConnection, id, tableName, function(idHasSensorInfo){ 
      if(idHasSensorInfo == false){ 
       callback(false); 
       return; 
      } 
      //in case user have all info in db, we get here and need to return false 
      if(i == sensorsTablesLength){ 
       callback(true); 
       return; 
      } 
     }); 
    } 
}; 


/*this function gets a user Id, and a single sensor table, and returns true if the user has information 
in the requested sensor table, otherwise returns false*/ 
exports.checkSingleSensorForId= function(dbConnection , id , sensorTable, callback){ 
    var myQuery = 'SELECT count(*) as IdCount FROM ' + sensorTable + ' WHERE id= ' + id; 
    var query = dbConnection.query(myQuery, function (err, row, result) {  
     console.log(query.sql); 
     if (err) { 
      console.log("checkSingleSensorForId error"); 
      console.error(err); 
      return; 
     } 
     var count= row[0].IdCount; 
     var idHasSensorInfo = (count > 0); 
     callback(idHasSensorInfo); 
    }); 
}; 

的console.log( 「idHasSensorsInfo爲:\ n」,idHasSensorsInfo);是一個調用3次的行,而應該只有一次。

有人有任何想法爲什麼,我需要做什麼來解決它?

回答

0

你有這樣一行:

DButils.checkAllSensorsForId(connection, 1 , tables , function(idHasSensorsInfo){ 
    console.log("idHasSensorsInfo is: \n" , idHasSensorsInfo); 
}); 

然後你有這樣的:

exports.checkAllSensorsForId= function(dbConnection, id , sensorsTables, callback){ 
    ... 
    for (var i = 0; i < sensorsTables.length; i++) { 
     ... 
     callback(); 
     ... 
    } 
}; 

所以回調線將被調用的,你叫它,多次而你的情況可能是3 - 它所做的就是從上面調用函數,這就是爲什麼你看到它調用3次。

我不知道正是你正在嘗試做的,但如果callback應該只被調用一次,確保其只跑了一次 - 它是否應該「取消」的for - 添加一個條件到for或每當你準備好時,使用promise來解決。