基于JavaScript系列的控制流程

时间:2014-02-28 19:29:08

标签: javascript node.js control-flow

在Mixu的Node.js一书中,有一个关于控制流的非常棒的部分。以下模式允许您将串联的异步请求链接起来,以确保在调用下一个事件之前已完成事件。我想修改它,以便一个异步请求的响应可以作为参数传递给下一个。

有什么想法吗?

http://book.mixu.net/node/ch7.html http://jsfiddle.net/B7xGn/

function series(callbacks, last) {
  var results = [];
  function next() {
    var callback = callbacks.shift();
    if(callback) {
      callback(function() {
        results.push(Array.prototype.slice.call(arguments));
        next();
      });
    } else {
      last(results);
    }
  }
  next();
}
// Example task
function async(arg, callback) {
  var delay = Math.floor(Math.random() * 5 + 1) * 100; // random ms
  console.log('async with \''+arg+'\', return in '+delay+' ms');
  setTimeout(function() { callback(arg * 2); }, delay);
}
function final(results) { console.log('Done', results); }

series([
  function(next) { async(1, next); },
  function(next) { async(2, next); },
  function(next) { async(3, next); },
  function(next) { async(4, next); },
  function(next) { async(5, next); },
  function(next) { async(6, next); }
], final);

1 个答案:

答案 0 :(得分:1)

您可以更改next功能签名,以便将其传递给result。这是你如何做到的。

function series(callbacks, last) {
  var results = [];
  function next(result) {
    var callback = callbacks.shift();
    if(callback) {
      callback(function(result) {
        results.push(Array.prototype.slice.call(arguments));
        next(result);
      }, result);
    } else {
      last(results);
    }
  }
  next();
}
// Example task
function async(arg, callback) {
  var delay = Math.floor(Math.random() * 5 + 1) * 100; // random ms
  console.log('async with \''+arg+'\', return in '+delay+' ms');
  setTimeout(function() { callback(arg * 2); }, delay);
}

function final(results) { console.log('Done', results); }

series([
  function(next) { async(1, next); },
  function(next, result) { console.log('result: ', result); async(2, next); },
  function(next, result) { console.log('result: ', result); async(3, next); },
  function(next, result) { console.log('result: ', result); async(4, next); },
  function(next, result) { console.log('result: ', result); async(5, next); },
  function(next, result) { console.log('result: ', result); async(6, next); }
], final);

编辑:

为了能够传递多个结果,您只需将系列函数更改为:

function series(callbacks, last) {
  var results = [];
  function next() {
    var callback = callbacks.shift(), args;
    if(callback) {
      callback.apply(this, (args = [
        function() {
          results.push(Array.prototype.slice.call(arguments));
          next.apply(this, arguments);
        }
      ]).concat.apply(args, arguments));
    } else {
      last(results);
    }
  }
  next();
}