0
function getUsernameAssociatedWithToken (token) {

    console.log('\n\t\tgetUsernameAssociatedWithToken');
    console.log("\t\t"+token);
    var userReturn = "";


    queryAsync(returnVal);

    function queryAsync(callback){
        connection.query("SELECT * FROM users WHERE token = '"+token+"'", function (error, results, fields) {

            if (error) {
                console.log(error);
                 callback(null);
            }

            if (results.length  > 0) {

                userReturn = results[0].user;
                callback(userReturn);


            } else {

                callback(null);
            }

        });
    };

    function returnVal(str){

    userReturn = str;
    console.log('vaaaaal');
    console.log(userReturn);

    }
    return userReturn;

}

在执行查询函数之前调用最后一个“return”(它不应该)。我将如何使用回调来做到这一点?

我试过这个,但这也失败了:

function getUsernameAssociatedWithToken (token) {

    console.log('\n\t\tgetUsernameAssociatedWithToken');
    console.log("\t\t"+token);
    var userReturn = "";




    function queryAsync(){
        connection.query("SELECT * FROM users WHERE token = '"+token+"'", function (error, results, fields) {

            if (error) {
                console.log(error);
                 return null;
            }

            if (results.length  > 0) {

                userReturn = results[0].user;
               return userReturn;


            } else {

                return null;
            }

        });
    };

return (queryAsync());

}
4

1 回答 1

3

您不能直接从函数返回异步调用的结果,因为(如您所见)函数在异步调用完成之前返回。相反,您的函数必须支持一个回调参数,当异步调用完成时,它将调用该参数以将结果返回给调用者。

function getUsernameAssociatedWithToken (token, callback) {
    ...
    queryAsync(callback);
}
于 2013-01-10T20:19:46.147 回答