0

I am building a user sign up and crud app. I have a db model.

var valid;
module.exports = {
    connectDB: function(){
    }
    ,
    findUser: function(req,res) {
    }
    ,
    createUser: function(email,name,password){
        var role = 'view';
        var sql = "INSERT INTO `users`(email, name, password, role) VALUES (" +  "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
        db.query(sql, function(err, result){
            if(err){
                console.log(`FAILED: ${err}`)
                return false; // tried setting valid to false
            }
            else
            {
                console.log(`User Created`);
                valid = true;

            }
        });
       return valid; // this also returns undefined 
    }
}

I want to be able to return a bool depending up on the succession of the query. I tried returning true/false. I did some searching on why this happens. Firstly there was an explanation about js being asynchronous. My question is what is the correct way of returning values in function when exporting so that I can use it?

sakib11
  • 496
  • 1
  • 5
  • 20
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – traktor Dec 08 '19 at 04:57
  • yes thanks. I was able to fix it after making it return a new promise and resolving when its done while rejecting when it failed. Wow. – sakib11 Dec 08 '19 at 05:14
  • 1
    lets not mention prepared queries – Lawrence Cherone Dec 08 '19 at 05:22
  • pardon? I dont understand. Should I have used backticks instead of " ? – sakib11 Dec 08 '19 at 05:26

1 Answers1

0

By using promises

    createUser: function(email,name,password){
        return new Promise(function(resolve,reject){
            var role = 'view';
            var sql = "INSERT INTO `users`(name, password, role) VALUES (" +  "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
            db.query(sql, function(err, result){
                if(err){
                    console.log(`FAILED: ${err}`)
                    reject(err);
                }
                else
                {
                    console.log(`User Created`);
                    resolve();
                }
            });
        })
    }

we can now use createUser like so;

 db.createUser(email,name,password).then(function(){
    console.log('redirect');
    res.redirect('/');
  }).catch(function(){
    console.log('something went wrong');
    res.render('signup', { message: 'something went wrong' })
  });
sakib11
  • 496
  • 1
  • 5
  • 20