@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
});
我會鼓勵你去嘗試的兩種方法,即使用回調和使用的承諾。希望你覺得它有用!
您需要使用回調策略來返回並解決貓鼬問題。 – Iceman
@ JJ9如果您的問題得到解答,請將答案標記爲已接受,不要讓它保持打開狀態 – orhankutlu