Is this right way to release the connection?

Viewed 444

As you know Node.js statements are async. So I write code in following way. But I can't make sure if the connection is released or not.

Why, because I'm writing connection.release() just after res.json(). In my view, once we send response the control doesn't pass to next statement (Query 1: Is it true?). So should I write it before I send response?

Query 2: res.json() / res.end() and connection.release() both are async methods. Is it true?

Query 3: Even if the following code works perfectly, can I write connection.release() only once, i.e., just when if else statement ends? If yes, why doesn't next() works after res.end()` in Node.js?

connection.query(query, [body.endDate, tripId], function (err, rows, fields) {
    if (err) {
        res.status(422).json(
            {
                status: "error",
                data: {error: {code: err.code, sqlMessage: err.sqlMessage}},
                message: "Something didn't work."
            }
        );
        connection.release();
    } else {
        res.status(200).json(
            {
                status: "success",
                data: {affectedRows: rows.affectedRows},
                message: "Trip ended."
            }
        );
        connection.release();
    }
});
0 Answers
Related