重构嵌套回调,node.js,async

时间:2012-07-17 00:33:17

标签: node.js asynchronous callback

function indexArticles(callback) {
  fs.readdir("posts/", function(err, files) {
    async.map(files, readPost, function(err, markdown) {
      async.map(markdown, parse, function(err, results) {
        async.sortBy(results, function(obj, callback) {
          callback(err, obj.date);
        }, function(err, sorted) {
          callback( {"articles": sorted.reverse()} );
        });
      });
    });
  });
}

我正在试图弄清楚如何使这个更漂亮 - 你可以说我正在使用caolan的异步库,但我不确定使用哪种控制流结构。例如,如果我使用async.waterfall,会产生相当多的代码,每个步骤都必须包含在匿名函数中。例如,这只是带有瀑布的嵌套版本的前两行:

function indexArticles(callback) {
  async.waterfall([
    function(callback) {
      fs.readdir("posts/", function(err, files) {
        callback(err, files)
      })
    },

    function(files, callback) {
      async.map(files, readPost, function(err, markdown) {
        callback(err, markdown)
      })
    }])
}

你会如何改善这一点?

如果有一种方法不仅从左边部分地应用参数,那么我可以看到,例如,

function indexArticles(callback) {
  async.waterfall([
    async.apply(fs.readdir, "posts/"),
    async.apply(async.map, __, readPost),
    async.apply(async.map, __, parse),
    // etc...
  ])
}

4 个答案:

答案 0 :(得分:6)

这是一个有趣的问题,因为您需要将参数绑定到迭代器函数的左侧和右侧,因此bind /也bindRight都没有(其中有一些实现)在StackOverflow上)将为你工作。这里有几个选项:

(1)首先,在您的async.waterfall示例中,您有:

function(callback) {
  fs.readdir("posts/", function(err, files) {
    callback(err, files)
  })
}

与:

相同
function(callback) {
  fs.readdir("posts/", callback)
}

使用Function.bind和此方法,可以编写整个函数indexArticles

function indexArticles(callback) {
  async.waterfall([
    fs.readdir.bind(this, 'posts/'),
    function(files, cb) { async.map(files, readPost, cb); },
    function(text, cb) { async.map(text, parse, cb); },
    function(results, cb) { async.sortBy(results, function(obj, callback) {
      callback(null, obj.date);
    }, cb) }
  ], function(err, sorted) {
    callback( {"articles": sorted.reverse()} );
  });
};

哪个更短。

(2)如果确实想要避免包装函数,则可以使用一种部分函数应用程序。首先,在文件的顶部(或在模块中等),定义一个名为partial的函数:

var partial = function(fn) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function() {
    var currentArg = 0;
    for(var i = 0; i < args.length && currentArg < arguments.length; i++) {
      if (args[i] === undefined)
        args[i] = arguments[currentArg++];
    }
    return fn.apply(this, args);
  };
}

此函数接受函数和任意数量的参数,并在调用函数时将参数列表中的undefined值替换为实际参数。然后你会像这样使用它:

function indexArticles(callback) {
  async.waterfall([
    fs.readdir.bind(this, 'posts/'),
    partial(async.map, undefined, readPost, undefined),
    partial(async.map, undefined, parse, undefined),
    partial(async.sortBy, undefined, function(obj, callback) {
      callback(null, obj.date);
    }, undefined)
  ], function(err, sorted) {
    callback( {"articles": sorted.reverse()} );
  });
}

因此,partial(async.map, undefined, readPost, undefined)返回一个函数,当异步库调用fn(files, callback)时,它会为第一个files和{{1}填充undefined }对于第二个callback,以对undefined的调用结束。

(3)this StackOverflow answerasync.map(files, readPost, callback)还有一个partial版本,允许您使用以下语法:Function.prototype;但是,我建议不要以这种方式修改async.map.partial(undefined, readPost, undefined),只需使用Function.prototype作为函数。

最后,由您决定哪种方法最具可读性和可维护性。

答案 1 :(得分:2)

看起来我和布兰登的回答有些重叠,但这是我的看法:

 var async = require("async")

//dummy function
function passThrough(arg, callback){
  callback(null, arg)
}

//your code rewritten to only call the dummy. 
//same structure, didn't want to think about files and markdown
function indexArticles(callback) {
  passThrough("posts/", function(err, files) {
    async.map(files, passThrough, function(err, markdown) {
      async.map(markdown, passThrough, 
        function(err, results) {
          async.sortBy(results, function(obj, callback) {
            callback(err, obj);
        }, 
        function(err, sorted) {
          callback( {"articles": sorted.reverse()} );
        });
      });
    });
  });
}
indexArticles(console.log)

//version of apply that calls 
//fn(arg, arg, appliedArg, apliedArg, callback)
function coolerApply(fn) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function () {
    var callback = Array.prototype.slice.call(arguments, -1)
    var otherArgs = Array.prototype.slice.call(arguments, 0, -1)
    return fn.apply(
      null, otherArgs.concat(args).concat(callback)
    );
  };
};

//my version of your code that uses coolerAppl
function indexArticles2(callback){
  async.waterfall([
    async.apply(passThrough, "posts/"),
    coolerApply(async.map, passThrough),
    coolerApply(async.map, passThrough),
    coolerApply(async.sortBy, function(obj, callback){callback(null,obj)})
  ],
  function(err, sorted){
    callback({"articles": sorted.reverse()})
  })
}
//does the same thing as indexArticles!
indexArticles2(console.log)

答案 2 :(得分:1)

到目前为止,这是我最终的结果。

function indexArticles(callback) {
  var flow = [
    async.apply(fs.readdir, "posts/"),

    function(data, callback) { async.map(data, readPost, callback); },

    function sortByDate(parsed, callback) {
      var iterator = function(obj, callback) {
        if (obj.date) { callback(null, obj.date); }
        else { callback("Article has no date.") }
      }
      // Note that this sorts in reverse lexicographical order!
      async.sortBy(parsed, iterator,
          function(err, sorted) { callback(err, {"articles": sorted.reverse()} ); }
        );
    }
  ];

  async.waterfall(flow, async.apply(callback))
}

答案 3 :(得分:1)

我最近创建了一个名为WaitFor的简单抽象,以同步模式调用异步函数(基于Fibers):https://github.com/luciotato/waitfor

我没有使用异步软件包对其进行测试,但它应该可行。如果您遇到问题,请与我联系。

使用wait.for和async你的代码将是:

var wait = require('waitfor');
var async = require('async');

function indexArticles(callback) {
  var files = wait.for(fs.readdir,"posts/");
  var markdown = wait.for(async.map, files, readPost);
  var results = wait.for(async.map, markdown, parse);
  var sorted = wait.for(async.sortBy, results, function(obj, callback) {
                                                  callback(null, obj.date);
                                              });
  callback( null, {"articles": sorted.reverse()} );
}

调用你的fn(异步模式):

//execute in a fiber
wait.launchFiber(indexArticles,function(err,data){
       // do something with err,data
       }); 

调用你的fn(同步模式):

//execute in a fiber
function handleRequest(req,res){
    try{
        ...
        data = wait.for(indexArticles); //call indexArticles and wait for results
        // do something with data
        res.end(data.toString());
    }
    catch(err){
        // handle errors
    }
}

// express framework
app.get('/posts', function(req, res) { 
    // handle request in a Fiber, keep node spinning
    wait.launchFiber(handleRequest,req,res);
    });