同步节点js功能

时间:2015-12-14 21:52:13

标签: javascript node.js asynchronous server

我对java脚本和节点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 is:\ n”,idHasSensorsInfo);是一个调用3次的行,而应该只调用一次。

有人知道为什么,以及我需要做些什么来解决它?

1 个答案:

答案 0 :(得分: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只应该调用一次,请确保它只运行一次 - 如果它应该取消&#39; for - 向for添加条件,或在您准备好时使用promise解决。