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