Javascript不会等待存储返回的值

时间:2016-01-04 13:54:26

标签: javascript node.js multithreading function timing

我想将函数的返回值存储到变量中并在之后使用它们但javascript不等待函数,所以当代码连续时它似乎未定义

NOT DUPLICATE IM NOT CALLBING CALLBACK

以下是代码:

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

1 个答案:

答案 0 :(得分:0)

似乎是一个错过的结束括号。

 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.