我问了我的问题,我得到了另一个答案,但我无法解决;(有人可以帮助我吗?
我的原始问题:How to access data from function (node.js)
我试着按照建议去做。它一直有效,直到 mongodb 中有一个集合。如果没有收集会怎样? 我收到一个错误
(node:18) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'userName' of undefined
有没有什么好的和简单的方法来确保即使没有集合我的函数也能正常工作?
我的 indeks.js
var userID = this.event.session.user.userId;
console.log(userID);
var self = this;
DbConn.dbFind("myUsers", userID).then(function(item) {
self.emit(':ask',
SpeechOutputUtils.pickRandom(self.t('WELCOME_OK', item.userName))
);
}, function(err) {
self.emit(':ask',
SpeechOutputUtils.pickRandom(self.t('WELCOME'))
);
});
我的 db.utilis
module.exports = {
dbFind: function(collectionName, userID) {
return MongoClient.connect(url).then(function(db) {
var collection = db.collection(collectionName);
return collection.findOne({alexaUserID:userID});
}).then(function(item) {
return item;
});
}
};
最佳答案
是的,有几件事你应该做。首先添加一个 catch 处理程序,而不是将第二个函数传递给 then
以获取返回的 promise 上的错误:
DbConn.dbFind("myUsers", userID)
.then(function(item) {
if (!item) {
// handle emtpy item her instead
// of using catch for program flow
return
}
self.emit(':ask',
SpeechOutputUtils.pickRandom(self.t('WELCOME_OK', item.userName))
);
})
.catch( function(err) {
// this will be an error that happens in the promise or the above then()
self.emit(':ask',SpeechOutputUtils.pickRandom(self.t('WELCOME')));
});
它更容易阅读,但更重要的是,catch()
将接收到上述 then()
中发生的错误,而其他模式则不会。
此外,我会直接在 then()
中测试 item
,而不是捕获错误并对其采取行动。以这种方式使用 catch 很难隔离真正的错误,例如错误的数据库连接。
关于javascript - Node.js mongodb 和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46918496/