0

我很确定这里的问题只是我还没有以必要的异步方式思考 Node.js。

userExists()在一个模块db中有一个函数,它在传递电子邮件时检查用户是否在数据库中,并返回trueor false

相关部分:

userExists : function(email) {
    var client = new pg.Client(app.conString);
    var query;
    var result = false;

    client.connect();

    query = client.query(
        "SELECT * FROM users WHERE email = $1",
        [email]
    );

    query.on('row', function(row) {
        result = true;
    });

    query.on('end', function() {
        client.end();
        return result;
    });

我这样称呼它:

if (!db.userExists(req.session.email)) {
        newUser();
    } else {
        updateUser();
    }
}

无论返回什么,它总是newUser()被调用。userExists()我该如何解决这个问题?

4

1 回答 1

1

你弄错时间了。函数运行后查询完成,因此您需要传递一个回调函数并“等待”结果。

userExists = function(email, cb) {
    var client = new pg.Client(app.conString);
    var query;
    var result = false;

    client.connect();

    query = client.query(
        "SELECT * FROM users WHERE email = $1",
        [email]
    );

    query.on('row', function(row) {
        result = true;
    });

    query.on('end', function() {
        client.end();
        cb(result);
    });
}


// Time 1: ask is the user exists
db.userExists(req.session.email, function(exists) {
    // Time 3: Yeah result came back
    if (exists) {
        updateUser()
    }
    else {
        newUser();
    }
});
// Time 2: I've asked, let's wait for the result
// The following code will likely be executed before you get the result back
于 2013-04-15T11:17:14.697 回答