Reputation: 7145
First I'm trying to insert data into the restaurant table.
After it finished (console log). It should call the second query (Insert audit). But it doesn't call that query and holds on the first function.
How do I fix this?
async function createRestaurant(req, res, next) {
const restaurant = {
name: req.body.name,
description: req.body.description
}
const audits = {
description: req.body.description
}
let query = "INSERT INTO restaurant SET ?";
await connection.query(query, restaurant, (error, results) => {
if (error) {
console.log("Error at res")
return true;
} else {
console.log("200 res")
return true;
}
});
let query2 = "INSERT INTO audits SET ?";
await connection.query(query2, audits, (error, results) => {
if (error) {
console.log("Error at audit")
} else {
console.log("200 res")
}
});
}
module.exports = {
createRestaurant: createRestaurant
}
Upvotes: 0
Views: 624
Reputation: 7145
You can't use async / await in every where. If you want use async / await it should be a promise. Since mysqljs is not a promised based library you can't use async / await here.
Upvotes: 0
Reputation: 2567
You should not use callback with async/await, the purpose of async/await is to write asynchronous code in a synchronous way. Indeed you can return an await call and use try/catch blocks.
In your example the function is returned in the first query callback, so the 2nd query is never reached.
async function createRestaurant(req, res, next) {
const restaurant = {
name: req.body.name,
description: req.body.description
}
const audits = {
description: req.body.description
}
try {
let query = "INSERT INTO restaurant SET ?";
let resRestaurant = await connection.query(query, restaurant);
console.log(200, 'resRestaurant');
let query2 = "INSERT INTO audits SET ?";
let resAudit = await connection.query(query2, audits);
console.log(200, 'resAudit');
return {resRestaurant, resAudit}; // You can return data here
} catch(e) {
console.log('err in requests', e); // you can also use try/catch block for each request
}
}
Upvotes: 2