同步节点js函数

synchronic node js function

本文关键字:函数 js 节点 同步      更新时间:2023-09-26

我对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次的行,而应该只调用一次。

有人知道为什么,我需要做些什么来修复它吗?

您有这行:

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进行解析。