2017-04-02 57 views
0

我有這個功能,會從我的數據庫中的一些數據,但我有一個麻煩調用函數獲得適當的響應快速的NodeJS異步問題

function getEvents() 
    { 
    var x = []; 
    var l = dbCollection['e'].find({}).forEach(function(y) { 
    x.push(y); 
    }); 

return x; 
}); 

和另一個函數調用該函數,但它始終返回undefined。 我如何使函數等到貓鼬完成填充數組?

感謝您的幫助! My life

+0

您需要使用回調策略來返回並解決貓鼬問題。 – Iceman

+0

@ JJ9如果您的問題得到解答,請將答案標記爲已接受,不要讓它保持打開狀態 – orhankutlu

回答

0

dbCollection['e'].find被稱爲非阻塞方式,因此您在填充前返回x。你需要使用回調或一些貓鼬的承諾。你可以從數據庫中的所有返回值,就像下面的代碼片段

function getEvents(callback) { 
    dbCollection['e'].find({}, function(error, results) { 
     // results is array. 
     // if you need to filter results you can do it here 
     return callback(error, results); 
    }) 
} 

每當你需要調用getEvents功能,你需要一個回調傳遞給它。

getEvents(function(error, results) { 
    console.log(results); // you have results here 
}) 

您應該閱讀貓鼬docs查詢如何工作。

還有支持承諾在貓鼬。您可以檢查this url以獲取有關承諾的更多信息。

0

@orhankutlu提出的解決方案應該可以正常工作。

我會給出另一個使用promise的解決方案。根據您的編程風格,您可以選擇這兩種解決方案之一。

解決方案使用的承諾:

function getEvents() { 
    return new Promise(function(resolve, reject){ 
     dbCollection['e'].find({}, function(error, results) { 
      if (error) return reject(error); 

      var x = []; 
      results.forEach(function(y){ 
       x.push(y); 
      }); 
      // forEach() is a blocking call, 
      // so the promise will be resolved only 
      // after the forEach completes 
      return resolve(x); 
     }); 
    }); 
}; 

調用getEvents():

getEvents().then(function(result){ 
    console.log(result); //should print 'x' 
}).catch(function(err){ 
    // Handle error here in case the promise is rejected 
}); 

我會鼓勵你去嘗試的兩種方法,即使用回調和使用的承諾。希望你覺得它有用!