Search code examples
javascriptnode.jsnode-mysql

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

    });

}

Solution

  • 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
      });
    }