How can we prevent return from stopping for loop in nodejs?

Viewed 48

Here is the code and when I run this it executes only One Time ...

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 can I run for loop or prevent it from stopping it ??

look this is how the function is working and in this when loop start it send response multiple time so i tried to set it out side of loop but now if i set response out side of loop then how can i send error in response

so i am 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 anything

You can use this. return makes the loop function to exist.

  export const postStock = (body) => {
    let values =  body.order.values();
    let sql = values.map((val) => `("${body.stocknum}", 
     "${JSON.stringify(val.cat_id)}", "${body.user_id}", 
     "${JSON.stringify(val.dyenumber)}", "${JSON.stringify(val.stockQty)}")`)
     let query = "INSERT INTO stockmaster (stocknum, cat_id, user_id, dyenumber, 
       stockQty) VALUES " + sql
    }
Related