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

后端 未结 6 2176
执念已碎
执念已碎 2021-02-08 22:28

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) {
  ht         


        
6条回答
  •  感情败类
    2021-02-08 23:07

    Don't use anonymous functions.

    EDIT

    Your code isn't even valid. You aren't closing most of your function calls.

    If you switched to named functions it would look something like this: Updated to reflected comment about global namespace

    (function () {
        app.get('/test', f0)
    
        function f0(req, res) {
          http.get('some/place', f1)
        }
    
        function f1(req1, res1) {
            if (res1.statusCode == 200) {
              res1.on('data', f2)
            }
         }
        function f2(data) {
            http.get('other/place?q=' + data, f3)
        }
        function f3(req2, res2) {
          if (res2.statusCode == 200) {
            res2.on('data', f4)
          }
        }
    
        function f4(data) {
              db.query(data).on('data', f5)
            }
    
        function f5(rows) {
            res.writeHead(200)
            res.end(JSON.stringify(rows))
        }
    })()
    

提交回复
热议问题