[英]Make functions for operations in mongodb
I need to make a function like this. 我需要做一个这样的功能。
function getDataFromCollection(collectionName) {
let data;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection(collectionName).find({}).toArray(function(err, result) {
data = result;
console.log(result);
db.close();
});
});
return data;
}
The problem is that data is undefined, but when I execute console.log(result), it works. 问题是数据是不确定的,但是当我执行console.log(result)时,它可以工作。 Any idea to help me.
有什么办法可以帮助我。 Thanks in advance.
提前致谢。
There's a very simple explanation. 有一个非常简单的解释。 The
function(err, result)
is essentially asynchronous and is not called immediately but after some time when the data is fetched from mongo. 该
function(err, result)
本质上是异步的,不会立即调用,而是在从mongo中获取数据后的一段时间。 The function(err, result)
is thus a callback. 因此,该
function(err, result)
是一个回调。 So, data
is not set to result immediately but after a while. 因此,不是将
data
设置为立即生成,而是需要一段时间。 Now, you return data immediately and don't wait for it to be populated (inside the function(err, result)
callback) so undefined
is obviously returned. 现在,您立即返回数据,而不必等待数据被填充(在
function(err, result)
回调内部),因此显然会返回undefined
。
The solution would be to use JavaScript's Promises
which lets you use asynchronous code and callbacks. 解决方案是使用JavaScript的
Promises
,它使您可以使用异步代码和回调。 We return a Promise
from getDataFromCollection
and chain a .then
when we call it. 我们从
getDataFromCollection
返回一个Promise
并链接一个.then
当我们调用它时。 The function or callback that is passed to the then
is executed when the promise is resolved inside the getDataFromCollection
function with the data that was passed to the resolve
function. 当在
getDataFromCollection
函数中使用传递到resolve
函数的数据解析promise时,将执行传递给then
的函数或回调。 Thus, the callback inside then
would be called when you receive the result
. 因此,里面的回调
then
当您收到将被称为result
。
All the code - 所有代码-
function getDataFromCollection(collectionName) {
return new Promise(function(resolve, reject) {
MongoClient.connect(url, function(err, db) {
if (err) {
reject(err);
return;
}
db.collection(collectionName).find({}).toArray(function(err, result) {
if (err) {
reject(err);
return;
}
console.log(result);
db.close();
resolve(result);
});
});
});
}
Consume the function like so. 像这样消耗函数。
getDataFromCollection("collection")
.then(function(result) {
// use result
})
.catch(function(err) {
console.log(err);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.