【问题标题】:Hoisting / Returning variable in Javascript [duplicate]Javascript中的提升/返回变量[重复]
【发布时间】:2018-06-10 11:12:08
【问题描述】:

我有以下代码来查询 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


    【解决方案1】:

    你需要更新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 语句,因为它与回调没有任何重要性。

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

    【讨论】:

    • 谢谢,对更好地理解回调非常有帮助。由于嵌套函数,我感到困惑。在 MongoClient.connect 函数范围之外提供“文档”需要什么?
    • 你可以使用一个全局变量(比如var docs_global)来解决这个问题。然后您可以将docs 的值分配给docs_global。但我不推荐这种做法。如果你需要维护一个全局状态,我建议使用新的 ES6 类语法
    【解决方案2】:

    改变这个 function() { console.log(docs); client.close(); }); 到这个

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

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

    【讨论】:

    • 非常感谢!两个答案都正确且有效?
    • 不客气,你能投票吗?
    猜你喜欢
    • 2019-05-07
    • 2015-02-27
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    相关资源
    最近更新 更多