@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