[英]Access variable outside mongoose find method - node js
In my node js program, I look into my mongoose database, and find and return the values in that collection - there is only one value. 在我的node js程序中,我查看了我的猫鼬数据库,然后查找并返回该集合中的值-只有一个值。
var myValueX;
myCollection.find(function(err, post) {
if (err) {
console.log('Error ' + err)
} else {
myValueX = post[0].valuex;
}
});
console.log('Have access here' + myValueX);
Now, I want to be able to use myValueX outside this find method. 现在,我希望能够在此find方法之外使用myValueX。 How can I do this? 我怎样才能做到这一点?
When I try the console.log above, I get undefined back - is this possible to achieve 当我尝试上面的console.log时,我得到了未定义的信息-这是否有可能实现
To access myValueX
after it had been assigned in find
's callback, you have two options, the first (naturally) is inside the callback itself, or inside a function called by the callback to which you send myValueX
as an argument. 要在myValueX
在find
的回调中分配后访问myValueX
,您有两个选择,第一个(自然地)在回调本身内部,或在回调中调用的函数内部,您将myValueX
作为参数发送给该函数。
The better solution in my opinion is to use promises. 我认为更好的解决方案是使用诺言。
A simple promise-using solution is as follows: 一个简单的使用承诺的解决方案如下:
function findPromise(collection) {
return new Promise((resovle, reject) => {
collection.find((err, post) => {
if (err)
return reject(err)
// if all you want from post is valuex
// otherwise you can send the whole post
resolve(post[0].valuex)
})
})
}
findPromise(collection)
.then((valueX) => {
// you can access valuex here
// and manipulate it anyway you want
// after it's been sent from the `findPromise`
console.log("valueX: ", valueX)
})
.catch((err) => {
console.log("An error occurred. Error: ", err)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.