Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop writing nesting code in node-mysql ( node.js, express, mysql )

Each time I throw a query, the nest depth increase by one, just like the code below. If I knew how to define a query as a function not in the action, the readability of my code would increase.

exports.getAll = function (req, res) {

    client.query('SELECT * FROM tag', function (err, result, fields) {
        client.destroy();

        if (err) {
            throw err;
        }

        var tag = result[0].tag;

        client.query('SELECT COUNT(follow_id) AS following_tag_num FROM follow WHERE user_id = ?', [req.session.user.user_id], function (err, result, fields) {
            client.destroy();

            if (err) {
                throw err;
            }

            res.render('hoge', {
                title: 'Welcome to Hoge',
                userInfo: req.session.user,
                tag: tag,
                following_tag_num: result[0].following_tag_num
            });
        });

    });

}
like image 699
Takehiro Adachi Avatar asked Jun 18 '26 14:06

Takehiro Adachi


1 Answers

Just make the handler a named function:

client.query(
  'SELECT COUNT(follow_id) AS following_tag_num FROM follow WHERE user_id = ?',
  [req.session.user.user_id],
  handleResult
);

function handleResult(err, result, fields) {
  client.destroy();

  if (err) {
    throw err;
  }

  res.render('hoge', {
    title            : 'Welcome to Hoge',
    userInfo         : req.session.user,
    tag              : tag,
    following_tag_num: result[0].following_tag_num
  });
}
like image 114
Guffa Avatar answered Jun 21 '26 03:06

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!