Omar Alqady Omar Alqady - 2 months ago 10
Javascript Question

Get result.insertId from callback function in node.js

I have the following code:

function qcallb(err,result){
console.log("result.insertID:"+result.insertId);
return result.insertId;
}

var createRecord= function (tableName,record){
try{
queryStatment="INSERT INTO " + tableName + " SET ?";
var result='';
var query = connection.query(queryStatment, record, qcallb,false);
}
catch(err){
return 0;
}
return iid;
}


I want to return the variable
result.insertId
from the callback function, to the function that calls create record, but I have not found a way to do this.

I tried to set a global variable in the callback function, but when I try to access it, its value is still unchanged.

Is there a way for me to either access the value directly in the callback function, or to have callback function notify me when it's called then return the value?




EDIT:

After testing every proposed solution here, and those that I found by searching elsewhere, the only thing that worked for me (without using external modules to make a piece of code run in 'sync' rather than 'async'), was to implement the logic I wanted inside the callback itself, which is what I wanted to avoid in the first place, but I couldn't work around it no matter what I did.





Answer

2 years later:

After getting much more experience with node.js and async code, I see how naive this question was, although it was beyond me at the time, which is also obvious in my using a try/catch block around an async call which is useless with async code, where handling errors is done by checking for err in the callback and acting upon it if it exists.

Since it seems to have quite a number of views, this seems to be a recurring issue for those newly introduced to async development.

This can't be done in the sense that was asked in the question, for an operation to occur after an async operation and use a value that is a result of the async operation, it has to be called from the callback of the async operation with that value.

To resolve the issue, the code can be modified to:

function doSomethingWithResult(result) {
  // query is done, and this would only be called if no error occurred
  console.log('Result is: ', result)
  // do whatever you want
}

function queryCallback(err,result) {
  if (err) {
    throw err
  }

  doSomethingWithResult(result)      
}

function createRecord(tableName, record) {
  queryStatment='INSERT INTO `' + tableName + '` SET ?'

  connection.query(queryStatment, record, queryCallback) 
}

---

Old Answer: After testing every proposed solution here, and those that I found by searching elsewhere, the only thing that worked for me (without using external modules to make a piece of code run in 'sync' rather than 'async'), was to implement the logic I wanted inside the callback itself, which is what I wanted to avoid in the first place, but I couldn't work around it no matter what I did.

Comments