0

I am unable to convert this code callback function to promises. When I am converting prototype to normal function it gives me an error, please help me to fix this error . I am trying to use the ES7 async-await feature to avoid callback.

function User() {};

User.prototype = {
    find : function(user = null, callback)
    {
        if(user) {
            let field = Number.isInteger(user) ? 'id' : 'username';
        }
        let sql = `SELECT * FROM users WHERE ${field} = ?`;
        pool.query(sql, user, function(err, result) {
            if(err) throw err

            if(result.length) {
                callback(result[0]);
            }else {
                callback(null);
            }
        }); 
    },
    create : function(body, callback) 
    {
        let pwd = body.password;
        body.password = bcrypt.hashSync(pwd,10);
        let bind = [];
        for(prop in body){
            bind.push(body[prop]);
        }
        // prepare the sql query
        let sql = `INSERT INTO users( fullname,email,birthday,gender,country,city,state,mobile,password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
        pool.query(sql, bind, function(err, result) {
            if(err) throw err;
            callback(result.insertId);
        });
    },

    login : function(username, password, callback)
    {
        this.find(username, function(user) {

            if(user) {
                if(bcrypt.compareSync(password, user.password)) {
                    callback(user);
                    return;
                }  
            }
            callback(null);
        });      
    }
}

module.exports = User;```
matthias_h
  • 11,356
  • 9
  • 22
  • 40
Akhil
  • 411
  • 4
  • 13

1 Answers1

1

You can also do it like this

pool.query(sql, bind)
.then((success) => {
    console.log(success);
})
.catch((error) => {
    throw err;
});
NikhilKrt
  • 76
  • 2
  • 3