【发布时间】:2015-12-07 05:08:38
【问题描述】:
我正在尝试使用带有 Bluebird 库的 Promise 重构我的 nodejs 服务器,但我遇到了一个简单的问题。
从我的数据库中获取用户后,我想列出与该用户关联的所有通知类:
不好的方式(工作......)
adapter.getUsers(function(users){
users.rows.forEach(function(item){
user = item.username;
adapter.getNotifications(user, function(notificationList){
console.log(notificationList);
})
});
});
Elegant Tentative Way (not working...)
var getNotifications = Promise.promisify(adapter.getNotifications);
adapter.getUsers().then(function(users) {
users.rows.forEach(function(item){
var dbUser = "sigalei/" + item.value.name;
console.log(dbUser);
return getNotifications(dbUser);
});
}).then(function(result){
console.log(result);
console.log("NOTIFICATIONLIST");
});
但是,当我执行此代码时,我的 getNotification 方法中出现此错误:
未处理的拒绝类型错误:无法读取未定义的属性“纳米” 在 Adapter.getNotifications (/Users/DaniloOliveira/Workspace/sigalei-api/api/tools/couchdb-adapter.js:387:30) 在 tryCatcher (/Users/DaniloOliveira/Workspace/sigalei-api/node_modules/bluebird/js/main/util.js:26:23)
编辑
在user2864740宝贵的cmets之后,我注意到这个错误与一些范围问题有关。那么,为什么在使用 promisify 方法后,getNotifications 方法不识别“this”环境变量?
var Adapter = module.exports = function(config) {
this.nano = require('nano')({
url: url,
request_defaults: config.request_defaults
});
};
Adapter.prototype.getNotifications = function(userDb, done) {
var that = this;
console.log(that);
var userDbInstance = that.nano.use(userDb);
userDbInstance.view('_notificacao', 'lista',
{start_key: "[false]", end_key: "[false,{}]"},
function(err, body) {
if(err){ done(err); }
done(body);
});
};
【问题讨论】:
-
嘿,错误是在“promisify”的getNotifications方法内部产生的。
-
@user2864740 再次,我编辑了问题,我认为问题与范围变量有关......
-
尝试使用
.call()ing 与adapter作为this。
标签: javascript promise bluebird