繁体   English   中英

Node.js mongodb 和 promises

[英]Node.js mongodb and promises

我问了我的问题,我得到了另一个答案,但我无法解决;(有人可以帮我吗?

我的原始问题: 如何从函数(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

模块.出口 = {

    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来处理返回的承诺中的错误:

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 使得很难隔离真正的错误,比如错误的数据库连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM