2017-02-24 15 views
0

期待どおりにコードが実行されない理由はわかりません。 UserExistが呼び出されると、関数コードで設定したステートメントの1つであるconsole.logが表示されます。 しかし結果は次のような画像です。もし誰かが助けることができたら謝ってください!
ConsoleノードJSコードが順番に実行されていない

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

コールバックが正しく連鎖していません。 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 
    }); 
} 
+0

ありがとうございます!できます!!!! –

+0

しかし、insertnewuserのパラメータが違うとどうなりますか? –

+0

コールバックに渡すパラメータが異なる場合は、さまざまな方法がありますが、重要なことは、コールバック関数内のパラメータとロジックをエンパセスし、コールバックに他のパラメータをフェッチすることです。例:func2(params、callback){//何かをしてfunc1(params)を呼び出します}; func1(params、callback){// paramsを使用してparams2を取得します}; async(http://caolan.github.io/async/)のようなライブラリの使用を検討してください。コードを整理するのに役立ちます。 –

関連する問題