0

Hello I am new to NodejS and still learning so I might have mistakes and I am trying to learn it by writing code and I am from java background. Asyc functions are still new to me.

Here is my question

I would like to assign user_id to each user from my code.

.post('/register', function (req, res, next) {
   var username = req.body.uname;
   var password = req.body.psw;
   var email = req.body.uemail;
   var fullname = req.body.fullname;
   var user_id = sql_counts.sql_count()+1;
   console.log('Your user id is'+user_id);
   sql_connection.User.create({
       username:username,
       password:password,
       email:email,
       user_id:user_id
   },function (err) {
       if(!err){
           console.log('Successful');
           res.redirect('/registrationComplete');
       }else{
           console.log('Error creating');
       }
   });
}); 

And here is my sql_count function:

function sql_count() {
    sql_connection.User.count().then(function (err) {
       initCounter =err;
    });
    return initCounter;
};

I would like to understand more about calls backs since this is very new and confusing to me. Could anyone suggest some materials,links,videos... Although it seems to be understanding in the start I just dont understand it when I try using it. And also how to return values from callbacks to outter function?

Say

In the code given above how do I return value from the 'then' part to outer function sql_count() ?

B A
  • 21
  • 5
  • You should define the `user_id` column as `autoincrement`, in that way each insert MySQL will generate new id. CREATE TABLE users ( user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ); – felixmosh Aug 27 '17 at 05:54
  • For understanding promises vs callbacks, take a look at this post: [Aren't promises just callbacks?](https://stackoverflow.com/a/22540276/5395709). Cheers! – M3talM0nk3y Aug 27 '17 at 05:57

2 Answers2

0

Use MYSQL AUTO_INCREMENT feature to create a new user_id for each new user (i.e each new row) while inserting as follows

CREATE TABLE USERS( user_id INT NOT NULL AUTO_INCREMENT);

cheers

For Callbacks and Promises checkout this video and for latest await /async feature this video

Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
0

You can use auto increment column in you mysql table it will automatically increase or generate id using random function. I will suggest you first one

Khemraj
  • 109
  • 1
  • 9