Reputation: 716
I'm making an app in angular & node.js. At a certain point of code I need to execute INSERT
query and then get back insertId
and then make another INSERT
into another table along with above insertId
. But i'm always getting 0
as insertId because it does not wait for first query to be executed due to its async nature. So I need a work around to wait for first query results and then execute second query. My code looks like below.
insert_users_query = `INSERT INTO users xxxxxx`;
connection.query(insert_users_query, (err, result)=>{
var user_id = result.insertId;
});
second_query = `INSERT INTO another_table (user_id) VALUES('${user_id}')`;
connection.query(linked_accounts_query, (err, result)=>{
// this query saves 0 as user_id in table.
});
I think this can be done via promises
. But as I'm beginner in this stuff and read an article on Promises
too but I can't figure out a simple solution. Any help will be highly appreciated!
Thanks.
Upvotes: 0
Views: 1453
Reputation: 2930
You can use async/await for this as well instead of calling 2nd query inside 1st as it creates mess when number of queries increases.
But since connection.query
returns a callback we need to wrap it inside a promise.
async function main(){
try{
const insert_users_query = `INSERT INTO users xxxxxx`;
const result = await queryDb(insert_users_query);
let user_id = result.insertId;
const linked_accounts_query = `INSERT INTO another_table (user_id) VALUES('${user_id}')`;
await queryDb(linked_accounts_query);
}
catch(e){
//catch error
}
}
You can call this generic queryDb
function returning promise
for all the queries.
function queryDb(query){
return new Promise( ( resolve, reject ) => {
connection.query(query, (err, result)=>{
if (err){
return reject( err );
}
resolve( result );
});
})
}
Upvotes: 1
Reputation: 2528
You can do same by.
insert_users_query = `INSERT INTO users xxxxxx`;
connection.query(insert_users_query, (err, result)=>{// query 1( getting insertId as result.insertId)
if(err){
//handle error
}else{
var user_id = result.insertId; // using insertId
second_query = `INSERT INTO another_table (user_id) VALUES('${user_id}')`;
connection.query(linked_accounts_query, (err, result2)=>{//query2
// this query saves 0 as user_id in table.
}
});
});
This is done by using callback you can use await
for the same.
This is bit simpler basically we will get err,result
as object after the execution of query1 and then we can run another query using err,result
of query1 in query1.
Upvotes: 1