我有一个在nodeJS内部有回调的方法,我试图在外部函数中设置一个值,该值可以与在回调中传递给 Mongoose 调用的数据结果一起返回:
'use strict';
var mongoose = require('mongoose')
,Alert = mongoose.model('Alert');
exports.getAllAlerts = function() {
var result = [];
Alert.find({}, function(err, alerts) {
if(err) {
console.log('exception while fetching alerts');
}
if(alerts) {
result = alerts;
console.log('result: ' + result);
}
});
return result;
}
如何使用 mongoose 回调中返回的警报值设置 result[] 的值?
提前致谢
最佳答案
很可能,find()
异步运行,在这种情况下,您将始终返回一个空数组,因为在您返回值时,它尚未定义也没有分配。
您需要重写您的 .getAllAlerts()
方法,以便它本身允许回调函数,例如
exports.getAllAlerts = function( cb ) {
Alert.find({}, function(err, alerts) {
if(err) {
console.log('exception while fetching alerts');
}
if(alerts) {
if( typeof cb === 'function' ) {
cb( alert || [ ] );
}
}
});
}
...你会以类似的方式使用它
YourModule.getAllAlerts(function( alerts ) {
console.log( alerts );
});
关于回调中的 JavaScript 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212685/