Node.js未处理的承诺拒绝

时间:2017-07-08 01:56:33

标签: javascript node.js passport.js q

我正在尝试使用passport使用node.js进行登录,但是当数据库中没有的用户名尝试登录时,我遇到了问题。我收到以下错误(node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a function

登录功能:

exports.login = function(username, password) {
    var deferred = Q.defer;

    MongoClient.connect(mongodbUrl, function(err, db) {
        var collection = db.collection('users');

        collection.findOne({'username' : username}).then(function(result) {
            if (result === null) {
                console.log('User not found:', username);
                deferred.resolve(false);
            } else {
                var hash = result.password;
                console.log('User found:', username);

                if (bcrypt.compareSync(password, hash)) {
                    deferred.resolve(result);
                } else {
                    console.log('Authentication for ' + username + 'failed');
                    deferred.resolve(false);
                }
            }

            db.close();
        });
    }).catch(err => console.log(err));

    return deferred.promise;
};

Passport.use功能:

passport.use('local-signin', new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    funct.login(username, password).then(function(user) {
        if (user) {
            console.log(user.username + 'logged in');
            req.session.success = 'Welcome, ' + user.username + '!';
            done(null, user);
        }

        if (!user) {
            console.log('Failed login attempt');
            req.session.error = 'Your Password or Username is incorrect! Please try again.';
            done(null, user);
        }
    }).fail(function(err) {
        console.log(err.body);
    });
}));

1 个答案:

答案 0 :(得分:3)

可以解决或拒绝承诺。您必须针对这两种情况进行编程。将.catch添加到代码的末尾,如下所示:

collection.findOne({'username' : username}).then().catch(err => console.log(err))