Node.js: What techniques are there for writing clean, simple callback code?

后端 未结 5 1752
醉酒成梦
醉酒成梦 2020-12-04 22:11

node.js code is known for turning into callback spaghetti.

What are the best techniques for overcoming this problem and writing clean, uncomplex, easy to understand

5条回答
  •  自闭症患者
    2020-12-04 22:42

    I'd suggest 1) using CoffeeScript and 2) using named callbacks and passing state between them in a hash, rather than either nesting callbacks or allowing argument lists to get very long. So instead of

    var callback1 = function(foo) {
      var callback2 = function(bar) {
        var callback3 = function(baz) {
          doLastThing(foo, bar, baz);
        }
        doSomethingElse(bar, callback3);
      }
      doSomething(foo, callback2);
    }
    someAsync(callback1);
    

    you can instead simply write

    callback1 = (state) -> doSomething state.foo, callback2
    callback2 = (state) -> doSomethingElse state.bar, callback3
    callback3 = (state) -> doLastThing state
    someAsync callback1
    

    once your doSomething, doSomethingElse and doLastThing have been rewritten to use/extend a hash. (You may need to write extra wrappers around external functions.)

    As you can see, the code in this approach reads neatly and linearly. And because all callbacks are exposed, unit testing becomes much easier.

提交回复
热议问题