0

I'm calling two functions, where first function is inserting the data in the table. I'm using mysql. The second one is count the value of the and display it.

The problem is, the second function is processing before inserting the table. What i'm doing wrong?.

My code is:

function_my(id);
console.log('id inserted');
count(id);

function_my(id){
  var mysql = require('mysql2');  
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'gcm',
  }); 
  for(var id=0; j < 10; j++){
    connection.query('INSERT INTO UserTable SET ?', {id : id}, function(err, res){
                if(err) throw err;
    });
}

count(id){
    connection.execute('select id from UserTable where id = ?', id , function(err, rows){
        console.log('Test :'+JSON.stringify(rows[0].id));
    });
}

the output is:

Test : undefined
Id inserted

why i'm facing the issue?

1 Answer 1

1

You should call count function after insert operation. count(id) should be used as the callback function, after all the records are inserted.

You may need to look into some Promise libraries (like bluebird) for more information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.