Nodejs Return Stop for Loop

Issue

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"
        })
    }

Solution

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

  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
    }

Answered By – brook yonas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published