回调函数内部无法访问变量

时间:2020-06-23 14:16:21

标签: javascript node.js mongodb child-process

我有一个变量deleteFlag,即使该变量的作用域是全局的,在函数内部也无法访问它。

说明(请同时引用我的代码):

在这里,我正在尝试获取MongoDB集合的详细信息,该集合存储了一个 date 文档(result[i].date)。变量difResult存储当前日期和从MongoDB获取的日期之间的差。假设difResult的值大于特定阈值,则处理相应的if-else条件。

我的if块,即if(difResult>20000)有一个child-process, exec函数和一个用于删除MongoDB集合的回调函数,现在在此函数中,我试图访问无法访问的var deleteFlag为什么?以及如何在函数内部进行访问?

app.js

MongoClient.connect("mongodb://localhost:27017/", {
  useUnifiedTopology: true
}, function(err, db) {
  if (err) throw err;
  var dbo = db.db("dbName");
  dbo.collection("colName").find({}).toArray(function(err, result) {
    if (err) throw err;
    for (var i = 0; i < result.length; i++) {
      var difResult = Math.round((today - result[i].date));
      var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
      console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
      console.log("Result Date " + result[i].date);
      if (difResult > 20000) {
        var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
          if (error !== null) {
            console.log('exec error: ' + error);
            return res1.status(500).json({
              error: "Failed!"
            });
          } else {
            MongoClient.connect("mongodb://localhost:27017/", {
              useUnifiedTopology: true
            }, function(err, db) {
              console.log("Delete Flag From Collection ", +deleteFlag.toISOString());
              //The above console log gives NaN or null value
              //Suggest that var deleteFlag is not accessible inside this callback function
              if (err) throw err;
              var dbo = db.db("dbName");
              var myquery = {
                date: deleteFlag
              };
              dbo.collection("colName").deleteOne(myquery, function(err, obj) {
                if (err) throw err;
                console.log("1 document deleted");
                db.close();
              });
            });
          }
        });
      } else {
        console.log("Else msg");
      }
    }
    db.close();
  });
});

1 个答案:

答案 0 :(得分:0)

您不必两次调用数据库,就可以优化代码并像这样使用它

    MongoClient.connect("mongodb://localhost:27017/", {
  useUnifiedTopology: true
}, function(err, db) {
  if (err) throw err;
  var dbo = db.db("dbName");
  dbo.collection("colName").find({}).toArray(function(err, result) {
    if (err) throw err;
    for (var i = 0; i < result.length; i++) {
      var difResult = Math.round((today - result[i].date));
      var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
      console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
      console.log("Result Date " + result[i].date);
      if (difResult > 20000) {
        var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
          if (error !== null) {
            console.log('exec error: ' + error);
            return res1.status(500).json({
              error: "Failed!"
            });
          } else {
          var myquery = {
                date: deleteFlag
              };
              dbo.collection("colName").deleteOne(myquery, function(err, obj) {
                if (err) throw err;
                console.log("1 document deleted");
              });
          }
        });
      } else {
        console.log("Else msg");
      }
    }
    db.close();
  });
});

但是,如果出于某种原因需要两次调用数据库,然后将deleteFlag值存储在数组中,然后在任意位置访问数组