Tôi đang cố gắng tinh chỉnh máy chủ nodejs của mình bằng lời hứa với thư viện Bluebird, nhưng tôi bị kẹt trong một vấn đề đơn giản.Cách đảm bảo "điều này" chính xác với Promise.promisify?
Sau khi chỉ khiến người dùng từ db của tôi, tôi muốn liệt kê tất cả lớp thông báo liên quan đến thành viên này:
Bad Way (làm việc ...)
adapter.getUsers(function(users){
users.rows.forEach(function(item){
user = item.username;
adapter.getNotifications(user, function(notificationList){
console.log(notificationList);
})
});
});
Elegant Way dự kiến (không hoạt động ...)
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");
});
Tuy nhiên khi tôi thực thi mã này tôi nhận được lỗi này trong phương pháp getNotification tôi:
Unhandled rejection TypeError: Cannot read property 'nano' of undefined at Adapter.getNotifications (/Users/DaniloOliveira/Workspace/sigalei-api/api/tools/couchdb-adapter.js:387:30) at tryCatcher (/Users/DaniloOliveira/Workspace/sigalei-api/node_modules/bluebird/js/main/util.js:26:23)
EDIT
Sau user2864740`s ý kiến quý báu, tôi nhận thấy rằng các lỗi có liên quan với một số vấn đề phạm vi. Vì vậy, tại sao sau khi sử dụng phương pháp promisify, phương thức dont getNotifications nhận ra biến "env" này?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);
});
};
Hey, lỗi được tạo bên trong phương thức getNotifications đang được "quảng bá". –
@ user2864740 Một lần nữa, tôi đã chỉnh sửa câu hỏi, tôi nghĩ rằng vấn đề có liên quan với các biến phạm vi ... –
Thử '.call()' ing nó với 'adapter' và' this'. – Amit