2017-07-19 32 views
1

Koaモジュールを使用しています - ノードjsとmysql &が問題になりました。サインアップ機能で (welcomeCtrl.js内側)関数の外で変数を使用できません

var bcrypt = require('bcrypt'); 
module.exports = { 
signup: function* (next) { 
bcrypt.genSalt(10, function(err, salt) { 
     console.log(salt); 
     bcrypt.hash(password, salt, function(err, hash) { 
      // Store hash in your password DB. 
      console.log(hash); //no error 
      var hashedPassword = hash; 
     }); 
     }); 
     console.log(bcrypt.hash.hash); //gives error 
      //or 
     console.log(bcrypt.hash.hahedPassword); //gives error 

     queryString = "insert into user(email,name, phone, password, course_id, dpt_id) values('%s','%s','%s','%s','%s','%s')"; 
     query = util.format(queryString, email, name, phone, hash, courseId, dptId); 
     results = yield databaseUtils.executeQuery(query); 
     this.redirect('/'); 
    } 
    } 

私はと異なるroutes.jsファイルにサインアップ後の関数を呼び出しています:ここで

router.post('/signup', welcomeCtrl.signup); 

databaseUtils.jsでexecuteQuerry機能が

ファイルであります
var executeQuery = function(query, callback) { 
pool.getConnection(function(err, connection) { 
    // Use the connection 
    connection.query(query, function(err, rows, fields) { 
     connection.release(); 
     if(err) { 
      err.mysqlQuery = query; 
      logger.logError(err); 
     } 

     if(typeof callback == "function") { 
      callback(err, rows); 
     } 
     // Don't use the connection here, it has been returned to the pool. 
    }); 
}); 
}; 
module.exports = { 
executeQuery: thunkify(executeQuery), 
executePlainQuery: executeQuery 
}; 

Is there any way to use hash variable outside the function so that it can be inserted in query?

答えて

1

のコールバックにクエリ関数を移動する必要があります。

bcrypt.genSalt(10, function(err, salt) { 
     console.log(salt); 

     bcrypt.hash(password, salt, function(err, hash) { 
     // Store hash in your password DB. 
     console.log(hash); //no error 
     queryString = "insert into user(email,name, phone, password, course_id, dpt_id) values('%s','%s','%s','%s','%s','%s')"; 
     query = util.format(queryString, email, name, phone, hash, courseId, dptId); 

     databaseUtils.executeQuery(query, function() { 
      this.redirect('/'); 
     }); 
     }); 
    }); 

問題は、どこredirect機能から来るんですか?関数をバインドしないかぎり、thisの文脈が緩んでしまいます。太い矢印の機能はあなたの設定で機能しますか?もしそうなら、あなたはそうすることができます。

+0

私もそれを試みましたが、それはエラーをスロー - 予期しない、(コンマ)後の結果= yield databaseUtils.executeQuery(クエリ); –

+0

あなたは実際に 'yield'を使うように設定されていますか?そうでなければ、おそらく古典的な約束に落ちるはずです。私は私の答えを更新します。 –

+0

はい 'yield'はすべて設定されていますが、時にはyield.renderを使ってHTMLページをレンダリングします。この場合はnoです。 –

関連する問題