Await似乎不起作用,异步(nodejs)

时间:2018-07-26 07:57:32

标签: node.js mongodb express asynchronous mean

因此,我试图创建一个函数来检查用户是否存在于数据库中,如果不存在,则将其导入到数据库中。我正在尝试使用等待功能,以便它在继续操作之前等待功能完成。

const doesUserExist = (id) => {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('db');
        var users = dbo.collection('user');
        return new Promise(function(resolve, reject) {
            users.findOne({'id': id}, function (err, user) {
                if (err) throw err;
                console.log('User: ', user);
                if (user === null) {
                    resolve(false);
                } else {
                    resolve(true);
                }
            });
        });
    });
}

const userLogin = async (user) => { // User login function
    var id = String(user.id);

    // Check if the user exists

    var doesExist = await doesUserExist(id);
    console.log(doesExist);
    if(doesExist===undefined){
        console.log('ERROR: Exist is empty');
        return;
    }
    if(doesExist===false){
        console.log(`User with the id ${id} does not exist.`);
        addUser(user);
    } else {
        console.log(`User with the id ${id} does exist.`);
    }
}

1 个答案:

答案 0 :(得分:2)

您不会从doesUserExist函数返回Promise。

您仅在MongoClient connect函数的回调中返回Promise。

您必须以这种方式重构代码:

const doesUserExist = (steamid) => {
    return new Promise(function(resolve, reject) {
        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db('treehouse');
            var users = dbo.collection('users');
            users.findOne({'steamid': steamid}, function (err, user) {
                if (err) throw err;
                console.log('User: ', user);
                if (user === null) {
                    resolve(false);
                } else {
                    resolve(true);
                }
            });
        });
    });
}

现在,doesUserExist函数返回的Promise将在findOne回调中得到解决。