2015-12-14 138 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来解决。