gpt4 book ai didi

javascript - Javascript 中的提升/返回变量

转载 作者:行者123 更新时间:2023-12-01 02:34:34 25 4
gpt4 key购买 nike

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

我想使用存储在变量文档中的查询结果进行进一步处理。但是它们不会从函数中返回。即表达式

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

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

最佳答案

您需要按如下方式更新 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 语句,因为它与回调一样没有任何重要性。

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

关于javascript - Javascript 中的提升/返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com