title: How do I avoid deeply nested code in node.js?
body: <p>In node.js, it being event-driven, all I/O is done via callbacks. So I end up writing code that looks like this:</p>
  
  <p><pre><code>app.get('/test', function (req, res) {
    http.get('some/place', function (req1, res1) {
      if (res1.statusCode == 200) {
        res1.on('data', function (data) {
          http.get('other/place?q=' + data, function (req2, res2) {
            if (res2.statusCode == 200) {
              res2.on('data', function (data) {
                db.query(data).on('data', function (rows) {
                  res.writeHead(200)
                  res.end(JSON.stringify(rows))
                })
              })
            }
          })
        })
      }
    })
  })
  </pre></code></p>
  
  <p>And that doesn't even include error handling.</p>
  
  <p>What can I do to unwind this mess?</p>