【问题标题】:Access variable outside mongoose find method - node js在猫鼬查找方法之外访问变量 - 节点js
【发布时间】:2017-02-03 02:07:53
【问题描述】:

在我的 node js 程序中,我查看了我的 mongoose 数据库,并在该集合中查找并返回值 - 只有一个值。

var myValueX;
myCollection.find(function(err, post) {
        if (err) {
            console.log('Error ' + err)
        } else {
            myValueX = post[0].valuex;
        }
    });

console.log('Have access here' + myValueX);

现在,我希望能够在这个 find 方法之外使用 myValueX。我该怎么做?

当我尝试上面的 console.log 时,我得到了 undefined ——这可能实现吗

【问题讨论】:

  • 否,因为console.log() 在查找操作完成并触发其回调之前运行。你必须改变代码的设计来做你想做的事情。

标签: javascript node.js mongoose


【解决方案1】:

要在find 的回调中分配myValueX 后访问它,您有两个选择,第一个(自然)在回调本身内部,或者在您发送@的回调调用的函数内部987654323@ 作为参数。

我认为更好的解决方案是使用 Promise。

一个简单的使用promise的解决方案如下:

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)
    })

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2018-02-17
    • 2015-11-19
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多