Search code examples
javascriptnode.jsnode-mysql

How can I assign result.insertId to id from function that i pass in query() function?


When i try to log id variable i get 'undefined'. How can I assign result.insertId to id from function that i pass in query() function?

var id;
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
  if (err) throw err;

  console.log(result.insertId);
  id = result.insertId;
});
console.log(id);

Solution

  • You're trying to log id before it's value is set in the query callback.

    Look at the comments below:

    var id;
    //this will execute immediately
    connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
        //this executes after the query returns
        if (err) throw err;
    
        console.log(result.insertId);
        id = result.insertId;
    }); 
    //this will execute next, BEFORE the query result is available
    console.log(id);