2017-02-02 43 views
0

在我的節點js程序中,我查看我的貓鼬數據庫,並查找並返回該集合中的值 - 只有一個值。訪問變量外貓鼬找到方法 - 節點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); 

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

當我嘗試上述的console.log,我得到了一個未定義回來 - 這是可能實現

+0

沒有,因爲'的console.log()'find操作完成,其回調被觸發之前運行。你必須改變代碼的設計來做你想做的事情。 –

回答

0

要訪問myValueX它在find的回調被分配之後,你有兩個選擇,第一(自然)位於回調本身內部,或者位於您將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) 
    })