簡體   English   中英

貓鼬查找方法外的訪問變量-Node JS

[英]Access variable outside mongoose find method - node js

在我的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);

現在,我希望能夠在此find方法之外使用myValueX。 我怎樣才能做到這一點?

當我嘗試上面的console.log時,我得到了未定義的信息-這是否有可能實現

要在myValueXfind的回調中分配后訪問myValueX ,您有兩個選擇,第一個(自然地)在回調本身內部,或在回調中調用的函數內部,您將myValueX作為參數發送給該函數。

我認為更好的解決方案是使用諾言。

一個簡單的使用承諾的解決方案如下:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM