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

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

    Several things can be done to avoid the 'matrioska-style'.

    • You can store callbacks to variables:

      var on_read = function (foo, bar) {
            // some logic 
          },
      
          on_insert = function (err, data) {
            someAsyncRead(data, on_read);
          };
      
      someAsyncInsert('foo', on_insert);
      
    • You can use some modules that help in those scenarios.

      // Example using funk
      var funk = require('funk');
      for(var i = 0; i < 10; i++) {
        asyncFunction(i, funk.add(function (data) {
          this[i] = data;
        }));
      }
      
      funk.parallel(function () {
        console.log(this);
      });
      

提交回复
热议问题