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

    });

}

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

You might look into several node flow control modules that are available to help curb the nesting. I like one called async. It provides a variety of ways to de-nest your nested code.

var async = require('async');
async.waterfall([
    function(callback) {
        client.query(sql, callback);
    },
    function(results, callback) {
        // do something with results, then call callback
    }],
    function(err, data) {
        // if any errors occur above, err is not null
        // otherwise 'data' is whatever got passed to the last callback
    });

async.waterfall takes a list of functions, and passes the results of each one on to the next, finally calling the second parameter, another function, with the final result. Results are passed not by returning them, but by a callback function. async also supports running several functions in parallel, in series, and a variety of different common patterns used in node.