为什么这个node.js代码不能串行执行?

时间:2015-04-30 09:19:48

标签: node.js sequence

我是一个总节点菜鸟,几乎不知道我在做什么。我正在尝试使用futures库依次执行一系列函数。我的代码:

var futures = require('futures');
var sequence = futures.sequence();

sequence
  .then(function() {
    console.log("one");
  })
  .then(function() {
    console.log("two");
  })
  .then(function() {
    console.log("three");
  });

我希望我的输出是

one
two
three

但我得到的输出是

one

我做错了什么?

2 个答案:

答案 0 :(得分:1)

Node.js正在处理回调函数,因此您需要以匿名方式传递它以使期货执行下一个函数:

var futures = require('futures');
var sequence = futures.sequence();

sequence
  .then(function(next) {
    console.log("one");
    next(null, 1);
  })
  .then(function(next) {
    console.log("two");
    next(null, 2);
  })
  .then(function(next) {
    console.log("three");
    next(null, 3);
  });

答案 1 :(得分:1)

futures正在不断变化和变化。为什么不使用更强大和更受欢迎的模块async。它拥有您可能需要的所有这些操作。

您所追求的是async.series https://github.com/caolan/async#seriestasks-callback

async.series([
    function(callback){
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback){
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results){
    // results is now equal to ['one', 'two']
});
相关问题