Here is the code, and when I run it, it only executes once…
export const postStock = (body) => {
for (let val of body.order.values()) {
let sql = ` INSERT INTO stockmaster (stocknum, cat_id, user_id, dyenumber, stockQty) VALUES ('${body.stocknum}', ${JSON.stringify(val.cat_id)}, '${body.user_id}', ${JSON.stringify(val.dyenumber)}, ${JSON.stringify(val.stockQty)})`;
return sql;
};
};
So, how do I run the for loop or prevent it from stopping?
Look at how the function works, and when the loop starts, it sends the response multiple times, so I tried to set it outside of the loop, but if I set it outside of the loop, how can I send an error in response?
So now I’m stuck here…!
static stock = async (req, res) => {
for (let i = 0; i < req.body.order.length; i++) {
const body = req.body;
connection.query(postStock(body, body.order[i]), (err, result) => {
if (err) {
res.status(500).json({
code: 0,
msg: "Fail",
emsg: "Server error: " + err.message
});
} else {
connection.query(updatepStock(body.order[i]), async (err, result) => {
if (err) {
res.status(500).json({
code: 0,
msg: "Fail",
emsg: "Server error: " + err.message
});
}
})
}
})
}
res.status(201).json({code: 1,msg: "success",emsg: "Stock arrived & Product Stock updated successfully"
})
}
2
Answers
return
stops execution and exits the function.return
always exits its function immediately, with no further execution if it’s inside a for loop.So you should avoid
return
in case you want the loop to continue. What you can do is store the sql into array or print the data without returning anythingYou can use this. return makes the loop function to exit.