Javascript中的提升/返回变量[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我有以下代码来查询MongoDB数据库:

   var docs;

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  findDocuments(db, function() {
    console.log(docs);
    client.close();
  });
});

const findDocuments = function(db, callback) {
    // Get the documents collection
    const collection = db.collection('oee');
    // Find some documents
    collection.find(query).toArray(function(err, docs) {
      assert.equal(err, null);
      console.log("Found the following records");
      //console.log(docs);
      callback(docs);
      return docs;   
    });
  };
}

哪个输出:

Connected successfully to server
Found the following records
undefined

我想使用存储在变量docs中的查询结果进行进一步处理。但是他们没有从函数返回。即表达式

   findDocuments(db, function() {
    console.log(docs);
    client.close();
  });

我得到一个“未定义”返回。我究竟做错了什么?

javascript node.js mongodb return hoisting
2个回答
2
投票

您需要更新findDocuments函数调用,如下所示,

findDocuments(db, function(docs) {
     console.log(docs);
     client.close();
});

您不需要顶部的docs变量。使用如下的局部变量,

const findDocuments = function(db, callback) {
     // Get the documents collection
     const collection = db.collection('oee');
     // Find some documents
     collection.find(query).toArray(function(err, docs) {
         assert.equal(err, null);
         console.log("Found the following records");
         return callback(docs);   
     });
 }

另请注意,我删除了return docs语句,因为它与回调一起没有任何重要性。

最后,我建议你更多地了解回调(最好是承诺)


0
投票

将此function() { console.log(docs); client.close(); });更改为此

function(docs) {
console.log(docs);
client.close();

});因为在您的代码中,您在代码顶部记录了docs变量,但没有收到任何值,请尝试使用新代码并告诉我。它现在有效吗?我想是的 。

© www.soinside.com 2019 - 2024. All rights reserved.