-2

I'm having difficulty understanding how works promise, I tried to create promise with express, to query on mysql and get results. I read that it is not cool to make this synchronous. I'm trying to make a little game, this route is for the registration.

var lang = require('../lang.js');
var config  =  require('../config.js');
var fieldValidator = require('../libs/field_validator');
var microtime = require('microtime');
var crypto = require('crypto');
//Presets
var lang = new lang();
var rlang = lang.returnMessage;
var fieldValidator = new fieldValidator();
var moment = require('moment');

module.exports = function(app, my){
    //Primeiro os registros
    /// Account Register
    ////
    var check_username = function(username){
        return new Promise(function(resolve, reject) {
            my.query('SELECT username FROM 4h_users WHERE ?', username, function (error, result, fields) {
                if (error) {
                    reject({"status": "error", "code":10 ,"message": rlang(lang, 10)});
                }else{
                    if(result.lenght > 0){
                        reject({"status": "error", "code":10 ,"message": rlang(lang, 10)});
                    }else{
                        resolve(true);
                    }
                };
            });
        });
    }
    check_username().then(function(id_user) {
      console.log(value);
    }, function(reason) {
      res.
    });


    app.post('/api/usuario/registrar', function(req, res){
        if(!req.body.lang){
            return res.send({"status": "error", "code":1 ,"message": 'Blank Language'});
        }else{
            var lang = req.body.lang;
        }
        if(!req.body.recode){
            return res.send({"status": "error", "code":4 ,"message": rlang(lang, 4)});
        }else if(!req.body.username){
            return res.send({"status": "error", "code":1 ,"message": rlang(lang, 1)});
        }else if(!req.body.password){
            return res.send({"status": "error", "code":3 ,"message": rlang(lang, 3)});
        }else if(!req.body.email){
            return res.send({"status": "error", "code":5 ,"message": rlang(lang, 5)});
        }else if(req.body.reemail != req.body.email){
            return res.send({"status": "error", "code":6 ,"message": rlang(lang, 6)});
        }

        my.query('SELECT email FROM 4h_users WHERE ?', req.body.email, function (error, result, fields) {
            if (error) {
                return res.send({"status": "error", "code":10 ,"message": rlang(lang, 10)});
            }else{
                return res.send({"status": "error", "code":13 ,"message": rlang(lang, 13)});
            };
        });

        if(!fieldValidator.username.isValid(req.body.username)){
           return res.send({"status": "error", "code":9 ,"message": rlang(lang, 9)});
        }else if(!fieldValidator.email.isValid(req.body.email)){
           return res.send({"status": "error", "code":7 ,"message": rlang(lang, 7)});
        }else if(!fieldValidator.password.isValid(req.body.password)){
           return res.send({"status": "error", "code":8 ,"message": rlang(lang, 8)});
        }

        var ip = generate_ip();
        var salt = crypto.createHash('sha256').update(microtime.now()+req.body.username).digest("hex");
        var password = crypto.createHash('sha512').update(salt+req.body.password).digest("hex");

        var user = {
            username: req.body.username,
            email: req.body.email,
            password: password,
            salt: salt,
            token_expiration: microtime.now(),
            money: config.default_bonus.money,
            hcoins: config.default_bonus.hcoins,
            register_date: moment().format('YYYY-MM-DD HH:mm:ss'),
            token: crypto.createHash('sha256').update(microtime.now()+req.body.username).digest("hex"),
            token_expiration: microtime.now()+config.expiration.login,
            offline_mode_expiration: 0
        };

        //Check if machine ip exists and generate another one
        check_ip_status(my, ip);

        // Time to mysql

        //Add new user to mysql
        my.query('INSERT INTO 4h_users SET ?', user, function (error, result, fields) {
            if (error) {
                console.log(error);
                return res.send({"status": "error", "code":10 ,"message": rlang(lang, 10)});
            }else{
                var machine = {
                    ip: ip,
                    id_user: result.insertId
                };
                //Add new machine to mysql
                my.query('INSERT INTO 4h_machines SET ?', machine, function (error, result, fields) {
                    if (error) {
                        console.log(error);
                        return res.send({"status": "error", "code":10 ,"message": rlang(lang, 10)});
                    }else{
                        return res.send({"status": "success", "code":11 ,"message": rlang(lang, 11)});
                    };
                });
            };
        });
    });
}


function generate_ip(){
    return (Math.floor(Math.random() * 254) + 1) + "." + (Math.floor(Math.random() * 254) + 1) + "." + (Math.floor(Math.random() * 254) + 1) + "." + (Math.floor(Math.random() * 254) + 1);
}
function check_ip_status(my, ip){
    my.query('SELECT ip FROM 4h_machines WHERE ?', ip, function (error, result, fields) {
        if (error) {
            return res.send({"status": "error", "code":10 ,"message": rlang(lang, 10)});
        }else{
            if(result.lenght > 0){
                ip = generate_ip();
                check_ip_status(ip);
            }
        };

    });
}
//id_user, username, salt, password, email, avatar_url, 4h_coins, money, last_login, register_date, token, token_expiration, reputation, actions, email_verify, modo_offline_expiration

and if you have another tips for this code please tell me, i'm learning and any help be very useful to me thanks

  • You should always wait for MySQL query results. So divide the code into pieces. Please read this page; https://blog.risingstack.com/asynchronous-javascript/ – Serkan KOCAMAN Feb 19 '17 at 22:41
  • 1
    You appear to be trying to send multiple responses to this request. When you do `my.query()` and then have an if/else in the response, you send a response with `res.send()` for all possible results there. Then, you also have `res.send()` later in your function. You can't do that. You send one response only per request. So, the logic flow here is just wrong. In addition, you need to continue your processing inside the `my.query()` callback, not after it. – jfriend00 Feb 19 '17 at 22:45

1 Answers1

2

if you have another tips for this code please tell me, i'm learning and any help be very useful to me thanks

This is a very general question which can be summarized as: How can I learn about promises. There are a lot of questions and answers on Stack Overflow about promises that I can recommend:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177