I am facing an issue where I need to retrieve a value after the completion of a for loop that is nested within an asynchronous function. The loop contains a query that inserts data into a database.
The function seems to be functioning correctly, but when I test it with Postman, the response comes back empty even though the values have been successfully inserted into the database.
This is how I invoke the function:
insertPractice(turno_id,req.body.practice_codes_list, practiceInsertQuery)
.then( result=> {
res.status(200).json({
"Added Practiced": result
})
}
)
And here is the implementation of the function:
async function insertPractice(turno_id, req, practiceInsertQuery){
//addedPractices="";
return new Promise((resolve, reject) => {
for (let i=0; i< req.length; i++){
connection.query(
practiceInsertQuery, [turno_id, req[i]],(error2, row2) => {
if (error2) {
console.log("Error inserting practice details:"+req[i] +" "+ error2);
practicesNotAdded += req[i] + "-";
}else{
console.log("Practice added""+req[i]);
addedPractices += req[i] + "-";
console.log("practices "+addedPractices);
}
});
console.log("inside for loop "+addedPractices);
}
resolve(addedPractices)
// Or handle error cases
reject("error");
})
The issue lies in the fact that the function does not wait for the query to complete, even though it successfully inserts values into the database. When testing with Postman, I receive an empty response like this:
https://i.sstatic.net/sKgsW.png
However, the values are indeed inserted into the database. What is the right approach to tackle this problem? I have tried using map instead of a for loop and now experimenting with promises, although unsure if my implementation is correct.
Here is the console output demonstrating that the console.log("inside for loop" + addedPractices) returns empty when there should be some values present: