节点js函数在执行其他函数之前返回

时间:2013-01-10 20:08:11

标签: node.js return

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());

}

1 个答案:

答案 0 :(得分:3)

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

function getUsernameAssociatedWithToken (token, callback) {
    ...
    queryAsync(callback);
}