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

后端 未结 5 1759
醉酒成梦
醉酒成梦 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:36

    Take a look at Promises: http://promises-aplus.github.io/promises-spec/

    It is an open standard which intended to solve this issue.

    I am using node module 'q', which implements this standard: https://github.com/kriskowal/q

    Simple use case:

    var Q = require('q');
    

    For example we have method like:

    var foo = function(id) {
      var qdef = Q.defer();
    
      Model.find(id).success(function(result) {
        qdef.resolve(result);
      });
    
      return (qdef.promise);
    }
    

    Then we can chain promises by method .then():

    foo()
    .then(function(result) {
      // another promise
    })
    .then(function() {
      // so on
    });
    

    It is also possible to creating promise from values like:

    Q([]).then(function(val) { val.push('foo') });
    

    And much more, see docs.

    See also:

    • http://jeditoolkit.com/2012/04/26/code-logic-not-mechanics.html#post
    • http://wiki.commonjs.org/wiki/Promises/A

提交回复
热议问题