节点JS代码没有按顺序运行

时间:2017-02-24 13:57:01

标签: sql node.js azure

我不知道为什么代码没有像我预期的那样运行。 当调用UserExist时,它应该是console.log我在函数代码中设置的一个语句。 但结果如下图所示。如果有人可以提供帮助,则表示赞成!! Console

var sql = require('mssql');
var config = require('./configuration/sqlconfig');

var Username = "Testing";

sql.connect(config);
console.log("Connected to DB");


if (!UserExist(Username)) {
    InsertNewRecord(Username);
}


function isEmptyObject(obj) {
    return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
    return true;
}

function UserExist(Username) { 
        console.log('Checking whether user exists or not... ');
        new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username =     '" + Username + "';")
        .then(function (recordset) {
            if (isEmptyObject(recordset)) {
                console.log("The User does not exist, ready to insert");
                return true;
            } else {
                console.log("The user is existed already.");
                return false;
            }
        }).catch(function (err) {
            //When errors come      
        });
}



function InsertNewRecord(Username) {
    console.log('Attempting to Insert records...');
    new sql.Request().query("INSERT INTO dbo.Embright_Users (Username) VALUES ('" + Username + "');");
    console.log("Added one new record");
}

1 个答案:

答案 0 :(得分:1)

回调未正确链接。 InsertNewRecord()应该作为回调传递给UserExist()函数,以确保按顺序执行。例如:

// Calling UserExist with a callback instead of 'if' statement
UserExist(Username, InsertNewRecord)

function UserExist(Username, callback) {
    console.log('Checking whether user exists or not... ');
    new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username =     '" + Username + "';")
    .then(function (recordset) {
        if (isEmptyObject(recordset)) {
            console.log("The User does not exist, ready to insert");
            // Calling InsertNewRecord with the username passed
            callback(Username);
        } else {
            console.log("The user is existed already.");
           // Do nothing
        }
    }).catch(function (err) {
        //When errors come   
    });
}