stackOverFlew
stackOverFlew

Reputation: 1499

Node js functon returning before other function is executed

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;

}

the last "return" is called before the query function is executed (its not supposed to). How would I do this using callbacks?

I've tried this but this also failed:

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

}

Upvotes: 0

Views: 134

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You can't directly return the result of an asynchronous call from a function because (as you've seen) the function returns before the asynchronous call completes. Instead, your function has to support a callback parameter that it will call to deliver the result back to the caller when the asynchronous call completes.

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

Upvotes: 3

Related Questions