0

I want to store the return values from functions to variable and use them after that but javascript doesn't wait for the function so when the code contiues it seems to be undefined

NOT DUPLICATE IM NOT TALKING ABOUT CALLBACK

Here's the code:

function register (name,user,pass)
{
    var userex = checkUserExistance(user);
    var nameex = checkNameExistance(name);
    var globalex = nameex || userex;
    var done = false;
    if (!(globalex)) {
        connection.query("INSERT INTO users (`name`,`user`,`pwd`) VALUES ('" + name + "','" + user + "','" + pass + "')", function (err, rows, fields) {
            if (!err) {
                done = true;
            } else {
                var today = new Date();
                console.log(today.toGMTString());
                console.log(err);
            }
            return { "ex": {"user":userex,"name":nameex}, "done": done };
        });
    }
}
Ziad Alzarka
  • 333
  • 1
  • 2
  • 12
  • Perhaps a better explanation is needed. There are two functions, which one is returning undefined? Please show the variable being assigned to, and the function call. –  Jan 06 '16 at 11:30
  • they both return value but javascript doesn't wait for them so it stays undefined till the function had completed – Ziad Alzarka Jan 06 '16 at 18:07
  • ok, then it's a duplicate as marked. Best wishes. –  Jan 07 '16 at 09:13

1 Answers1

0

Seems to be a missing closing bracket.

 function register (name,user,pass)
 {
    ...
    if (!(globalex)) {
        connection.query("INSERT INTO users (`name`,`user`,`pwd`) VALUES ('" + name + "','" + user + "','" + pass + "')", function (err, rows, fields) {
        if (!err) {
            done = true;
        } else {
            var today = new Date();
            console.log(today.toGMTString());
            console.log(err);
        }

        // *** Returning from the anonymous function ***
        return { "ex": {"user":userex,"name":nameex}, "done": done };
    }); // *** End of anonymous function
} // *** end if ***

// Still inside the register() function here, no value returned.
  • Yes, there's a `}` missing from the posted code, but the return statement is still within the callback supplied to `connection.query` and isn't going to be returning from `register`, so this doesn't really answer the underlying problem. I suspect the OP needs to start passing a callback to `register`, as discussed in the duplicate question. – James Thorpe Jan 04 '16 at 14:05
  • don't care about it i just copied it fast this is not the error ! – Ziad Alzarka Jan 05 '16 at 13:01