Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid deeply nested code in node.js?

Tags:

node.js

In node.js, it being event-driven, all I/O is done via callbacks. So I end up writing code that looks like this:

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

And that doesn't even include error handling.

What can I do to unwind this mess?

like image 799
nornagon Avatar asked Feb 04 '11 21:02

nornagon


People also ask

What is deep nesting in coding?

Nesting Depth. Background. The nesting depth is the number of statement blocks that are nested due to the use of control structures (branches, loops). We will discuss the nesting depth at the level of a procedure (method). Implementations must not occur at other points.

Why you shouldn't use node JS?

Applications with heavy computing server-side. Since Node. js uses only one CPU core, heavy computations on the server will block all other requests. In this case, the event-driven non-blocking I/O model which is the strongest side of Node. js will become useless, and the application performance will suffer.

Which is the best option to describe node JS?

Node. js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node. js is an open source, cross-platform runtime environment for developing server-side and networking applications.


1 Answers

You could use async module to avoid this.

like image 88
Alfred Avatar answered Oct 24 '22 22:10

Alfred