Node.js/Async - How to avoid callback hell with async?

前端 未结 3 1928
一生所求
一生所求 2021-01-12 04:55

I\'m new to Node.Js and JavaScript web development on the backend. I see that callbacks inside callbacks could be a pain and there are modules to avoid that. One of these mo

3条回答
  •  再見小時候
    2021-01-12 05:46

    There are ways to combat runaway nesting using functional programming techniques. I use the curry module to break loop bodies out into stand-alone routines; usually this carries a very minor performance hit versus nesting (study curry for why). Example:

    var curry = require('curry'),
        async = require('async');
    
    var eachBody = curry(function(context, item, callback) {
      callback(null, context + item);  // first argument is error indicator
    });
    
    function exampleLoop(data, callback) {
      // use the curried eachBody instead of writing the function inline
      async.map(data, eachBody(data.length), callback);
    }
    
    function print(err, result) {
      console.log(result);
    }
    
    exampleLoop([2, 4, 6], print);  // prints [5, 7, 9]
    exampleLoop([2, 4, 6, 7], print);  // prints [6, 8, 10, 11]
    

    Instead of:

    var async = require('async');
    
    function exampleLoop(data) {
      async.map(data, function(item, callback) {
        callback(null, data.length + item);  
      }, function(err, result) {
        console.log(result);
      });
    }
    
    exampleLoop([2, 4, 6]);  // prints [5, 7, 9]
    exampleLoop([2, 4, 6, 7]);  // prints [6, 8, 10, 11]
    

    The second example is more compact, but the more nesting you add, the less readable it becomes. Also, by splitting up the implementation, you can reuse component functions in multiple ways, and you can write unit tests for the individual component functions, not only for the high-level functionality.

提交回复
热议问题