nodeJS 从回调返回值

2022-01-03 00:00:00 node.js callback mysql

我正在构建一个应用程序,在该应用程序中,在进行特定调用时,我必须阻止并等待身份验证查询的结果,然后才能继续.

I am building an application in which on a particular call, i must block and wait for the results from an authentication query before coninuing.

function authenticate(userid, hash)
{
    mysql_client.query("SELECT `hash` FROM `auth` WHERE `userid` = " + userid, function selectCb(err, results, fields) {
    if (err)
    {
      client.send("Error communicating with mysql, please retry your request");
      return false;
    }

    if(results.length == 0 || results[0].hash != hash)
    {
        client.send("Error comparing authentication data with database, please retry request");
        return false;
    }

    return true;
}
);
}

我希望能够从 authenticate() 函数本身返回这些值,而不是从内部匿名函数 selectCb 返回这些值,并且在回调完成之前具有身份验证块.我该怎么做?

I want to be able to return those values from the authenticate() function itself, not the internal anonymous function selectCb and have authenticate block until the callback is complete. How can I go about doing this?

推荐答案

你的外部函数需要提供一个回调本身,一旦 mysql 调用完成就可以执行它.类似的东西:

Your outer function needs to provide a callback itself which can be executed once the mysql call is done. Something along the lines of this:

function authenticate(user, pass, callback) {
    mysql_client.query("...", function (err, results, fields) {
        if (err) {
            callback("Error communicating ...");
        } else if (results.length ...) {
            callback("Error comparing authentication...");
        }
        callback()
    });
});

示例用法:

authenticate('jim', '123456', function (err) {
    if (err) {
        alert(err);
    } else {
        alert('Welcome');
    }
}); 

相关文章