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

后端 未结 6 2167
执念已碎
执念已碎 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:13

    I wrote a library based on node-seq, which looks like this:

    app.get('/test', function (req, res) {
      Seq()
        .seq(function () {
          http.get('some/place', this.next)
        })
        .seq(function (req1, res1) {
          if (res1.statusCode == 200) {
            res1.on('data', this.next)
          }
        })
        .seq(function (data) {
          http.get('other/place?q=' + data, this.next)
        })
        .seq(function (req2, res2) {
          if (res2.statusCode == 200) {
            res2.on('data', this.next)
          }
        })
        .seq(function (data) {
          db.query(data).on('data', this.next)
        })
        .seq(function (rows) {
          res.writeHead(200)
          res.end(JSON.stringify(rows))
        })
    })
    

    The code is here.

    Also, there's a lengthy discussion on the nodejs mailing list about this issue.

    Step is another library for doing this stuff.

提交回复
热议问题