I want to write a nested callback JavaScript in order to use the subsequent ID’s of the INSERT statements in the different SQL tables. My code looks as follows:
db.promise().query( // create Place with auto-generated PlaceID `INSERT INTO Place (Street,PLZ) VALUES('${street}', ${plz})` , (err,result) => { db.promise().query( // insert User using PlaceID `INSERT INTO User (PlaceID, Name, Created_On) VALUES(${result.insertID}, '${name}',current_timestamp())` , (err,result) => { // insert Account using UserID `INSERT INTO Account (UserID, Email, Password, Created_On) VALUES(${result.insertID}, '${email}', '${pwd}', current_timestamp())` } ); } );
However, when trying to run this with Node.js it says Error: Callback function is not available with promise clients
.
Do you have a solution to retrieve the insert IDs for the following INSERTS?
I’ve also tried with .then((result)=>{..})
which seems to work but the result.InsertID is always undefined?
// create place with auto-generated PlaceID db.promise().query(`INSERT INTO Place (Street,PLZ) VALUES('${strasse}', ${plz})`) .then((err,result) => { if(err)throw err; // insert User using PlaceID db.promise().query( `INSERT INTO User (PlaceID, Name, Created_On) VALUES(${result.insertID}, '${name}',current_timestamp())`) .then((err,result) => { if(err)throw err; // insert Account using UserID db.promise().query(`INSERT INTO Account (UserID, Email, Password, Created_On) VALUES(${result.insertID}, '${email}', '${pwd}', current_timestamp())`) }); }).catch((err)=>{console.log(err)});
Advertisement
Answer
Turns out it has to be result.insertId
instead of result.insertID
and then it doesn’t return NULL anymore..