Javascript Node.js mongodb和承诺
我问了我的问题,别人又给了我另一个答案,但我无法回答;有人能帮我吗 我最初的问题是: 我试着按照建议去做。它一直工作到mongodb中有一个集合。如果没有集合会发生什么? 我有个错误Javascript Node.js mongodb和承诺,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我问了我的问题,别人又给了我另一个答案,但我无法回答;有人能帮我吗 我最初的问题是: 我试着按照建议去做。它一直工作到mongodb中有一个集合。如果没有集合会发生什么? 我有个错误 (node:18) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'userName' of undefined 有没有什么好的简单的
(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处理程序,而不是将第二个函数传递给
,然后在返回的承诺中传递错误:
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()
中测试项,而不是捕获错误并对其执行操作。使用catch这种方式很难隔离真正的错误,例如坏的DB连接