您可能没有正确地将上下文传递给方法,正确的方法是直接在 Mongoose 原型上提供方法的承诺版本:
// I assume that methods you're using are set on mongoose.Model,
// but be sure to check, maybe, they're using some other prototype (!)
var promisify = require('deferred').promisify;
var modelProto = mongoose.Model.prototype;
modelProto.pFind = promisify(modelProto.find);
modelProto.pFindById = promisify(modelProto.findById);
// After that you may use promisified methods directly:
app.get('/apps', requireLogin, function (req, res) {
AppPermissions.pFind({ user: req.user.id, valid: true })
.map(function (permission) {
return ApplicationRecord.pFindById(permission.application)(
function (application) {
application.permission = permisson;
return application;
}
);
}).end(function (applications) {
res.render('applist', { applications: applications });
}, null);
});
您还可以避免污染原型,并间接使用方法:
var promisify = require('deferred').promisify;
var modelProto = mongoose.Model.prototype;
var pFind = promisify(modelProto.find);
var pFindById = promisify(modelProto.findById);
app.get('/apps', requireLogin, function (req, res) {
pFind.call(AppPermissions, { user: req.user.id, valid: true })
.map(function (permission) {
return pFindById.call(ApplicationRecord, permission.application)(
function (application) {
application.permission = permisson;
return application;
}
);
}).end(function (applications) {
res.render('applist', { applications: applications });
}, null);
});