Calling a nested query. I need to call 2 queries in one api call in node js. I am using npm mysql library. 1st query runs but the 2nd don't. How can i run both queries one by one?
router.delete("/:id", async (req, res) => {
conn.query(
"Delete FROM assignedcourses WHERE CourseID = ?",
req.params.id,
async (err, results) => {
if (err) throw err;
conn.query(
"Delete FROM courses WHERE CourseID = ?",
req.params.id,
async (err, results) => {
res.send(results);
}
);
}
);
});
You can run the commands "parallel" with promises.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
router.delete("/:id", (req, res) => {
Promise.all([
new Promise((resolve, reject) => {
// execute query
conn.query("Delete FROM assignedcourses WHERE CourseID = ?", req.params.id, (err, result) => {
if(err){
return reject(err);
}
// query done
resolve(result);
});
}),
new Promise((resolve, reject) => {
// execute query
conn.query("Delete FROM courses WHERE CourseID = ?", req.params.id, (err, results) => {
if(err){
return reject(err);
}
// query done
resolve(result);
});
}),
]).then((results) => {
// do something with both results
res.send(results);
}).catch((err) => {
// handle query errors here
res.status(500).end(err.message);
});
});
There is no need for the async keyword.
Related
I'm currently a little confused as to how to properly wait for the promise to finish before returning the result from a query
Here is my current code:
const getLeaderboardValues = async () => {
const SQLConnection = await getSQLConnection();
return new Promise((resolve, reject) => {
SQLConnection.query(getValuesSQLQuery, (err, result) => {
if (err) { reject(err) }
return resolve(result);
});
SQLConnection.end()
})
}
const runtime = () => {
getLeaderboardValues().then((result) => {
console.log(result);
})
}
The code above does log the correct results while debbugging, i believe this is because i'm giving the code more time to render with the breakpoints, however when running normally i get undefined
I believe the SQLConnection.end() line is executing before the query is returned, given it is outside the query statement.
The below may solve your issue, however I do not recommend opening a connection and closing it on every request in production systems.
const getLeaderboardValues = async () => {
const SQLConnection = await getSQLConnection();
return new Promise((resolve, reject) => {
SQLConnection.query(getValuesSQLQuery, (err, result) => {
if (err) {
reject(err)
return SQLConnection.end()
}
SQLConnection.end()
return resolve(result);
});
})
}
const runtime = () => {
getLeaderboardValues().then((result) => {
console.log(result);
})
}
can anyone help me.
I need to get result of queryA [which is an update query that returns ROW_COUNT( )], see if the result is equal to 1.
If not, just return it via res.json
If yes, call queryB [which returns a set of rows].
After which, I have to loop and call queryC to update each row. It has to be one at a time because the queryC is also inserting auditTrails within the stored procedure.
This is the source code:
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*GET rows to be updated*/
const GetRows = connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE rows*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
});
});
});
}
res.json(updateCus);
connection.end();
});
Error:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Query'
then another one at the bottom:
throw er; //Unhandled 'error' event
You are missing 'await' before the mysql.createConnection(config) and connection.query call, since these are asynchronous functions. Also in your code connection.end() should be inside the callback.
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = await mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = await connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
connection.end();
if (error) {
return console.error(error.message);
}
});
});
});
}else{
connection.end();
return res.status(200).json({
customer:updateCus});
}
});
I know the database is connecting with the code as, when i console.log(res) with the code below it is returning the correct data,
const orm={
selectAll(){
connection.query('SELECT * FROM burgers', (err,res) => {
if (err) throw err;
console.log(res)
return res;
});
},
Yet when i console.log(burgers) from this function in the code below it is returning an undefined
app.get(`/`, function (req, res) {
const burgers = orm.selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
I understand this may be a very simple answer but i personally just cannot work it out any help is welcomed.
selectAll is using a callback style method inside it. You can not get the response syncronously. You need to either pass the callback to selectAll or change it to use promise like this
function selectAll() {
return new Promise((reoslve, reject) => {
connection.query("SELECT * FROM burgers", (err, res) => {
if (err) {
reject(err);
}
reoslve(res);
});
});
}
You can then use it like this
app.get(`/`, function async (req, res) {
const burgers = await selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
Your selectAll method will not return any value.
query get an lambda callback function as second parameter AND query is asyncron
One way is to return an Promise from selectAll
const orm = {
selectAll(callback) {
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM burgers', (err, res) => {
if (err) {
reject(err);
} else {
resolve(res)
}
})
})
},
Than you can get your result:
app.get(`/`, function (req, res) {
orm.selectAll().then( burgers => {
console.log(burgers)
res.render(`index`, burgers);
});
});
I have this function that make query to MySQL:
const getAllUserReports = (userID) => {
return new Promise((resolve, reject) => {
connection.query(
`SELECT reports.id,report_types.name,companies.id as companyID,reports.year,reports.deadLine
FROM reports
INNER JOIN report_types ON reports.typeID=report_types.id
INNER JOIN companies ON reports.companyID=companies.id
WHERE reports.creatorUserID=${userID} and reports.active
`,
(err, result) => {
if (err) reject(err);
resolve(result);
}
);
});
};
and more function like this. I want to change it to function that get the query from external file and just make the call. Example:
// Get report by ID
const getReportByID = (query,reportID) => {
return new Promise((resolve, reject) => {
connection.query(query(reportID),
(err, result) => {
if (err) reject(err);
resolve(result);
}
);
});
};
const getQuery = async (reportID) => {
const query = await readFromFileOrOtherPlace(reportID);
return doSomeValidatingParsingEtc(query);
};
const getReportByID = (reportID) => {
return new Promise(async (resolve, reject) => {
let query = await getQuery(reportID);
connection.query(query,
(err, result) => {
if (err) reject(err);
resolve(result);
}
);
});
};
I trying to execute 2 MySQL queries sequentially in Node.JS. MySQL queries work properly by itself.
I would like to do it with async/await function to be sure record is inserted before it's updated.
Here is the code:
router.post('/assign_new_item_id', async (req, res) => {
.....
try {
let qr1= "INSERT INTO foo1 ........;"
await pool.query( qr1, (err) => {
if (err) throw err;
});
let qr2= "UPDATE foo1 .....;"
await pool.query( qr2, (err) => {
if (err) throw err;
});
}catch(err){
console.log(err)
}
It seems that execution "hangs" within first await await block. What is the best way the ensure that both queries are executed consequently.
Thanks in advance for any help.
To await you need a Promise, Not Callback. In your case you are not returning a promise to await.
router.post('/assign_new_item_id', async (req, res) => {
// .....
try {
let qr1 = "INSERT INTO foo1 ........;"
await new Promise((res, rej) => {
pool.query(qr1, (err, row) => {
if (err) return rej(err);
res(row);
});
});
let qr2 = "UPDATE foo1 .....;"
await new Promise((res, rej) => {
pool.query(qr2, (err, row) => {
if (err) return rej(err);
res(row);
});
});
} catch (err) {
console.log(err)
}
});
Here I am promisifing the pool.query method and returning a promise.