【问题标题】:how to synchronize 2 async.waterfalls如何同步 2 async.waterfalls
【发布时间】:2014-01-06 00:17:13
【问题描述】:

我有一组必须按顺序读取的命令。任何失败,处理停止。

readCommands 是一个读取函数数组...

async.waterfall(readCommands, function(err) {
    if (err) {
        console.log(err);
        res.send(500, { error : err.toString() });
        return;
    }
    else {
        console.log('we determined the state to which we have to rollback to');
    }
});

在这一点上,我知道我是从什么开始的。现在我想做写命令

async.waterfall(writeCommands, function(err) {
    if (err) {
        console.log(err);
        res.send(500, { error : err.toString() });
        return;
    }
    else {
        console.log('we succeeded with all the write commands...');
    }
});

数组 readCommands 和 writeCommands 条目完全不同,因此很难将它们组合起来。但我会在去下一个瀑布之前完成第一个瀑布。 如何从现有的两个中制作“瀑布”?

【问题讨论】:

  • 您从readCommands 收集的数据是否用作writeCommands 的输入?
  • 承诺!这就是你想要的。 promises-aplus.github.io/promises-spec
  • @Nate,不,他们是独立的
  • @Sukima,我想过把每一个瀑布都变成一个承诺,你是这个意思吗?我真的不希望在这个函数中进行任何处理,直到首先完成读取然后写入,然后才进行更多的同步调用。这就是为什么每个瀑布都不能被承诺所取代的原因。一方面,第一个瀑布的异常处理与第二个完全不同
  • @Nate 我从字面上解释了“我如何从现有的两个中制作一个“瀑布””。但是,您可以改用series,因为使用waterfall 没有任何好处。我已经更新了我的答案。

标签: javascript node.js asynchronous node-async


【解决方案1】:

只需组合你的两个数组,它们就会按顺序运行:

async.waterfall(readCommands.concat(writeCommands), function(err) {...}

【讨论】:

  • 这很好用,但现在我必须传递一个结果变量。所以每个成功的调用都需要有回调(null,anotherdataelement)。当我如上所述进行调用时,我得到 Object is not a function。任何想法如何解决这个问题?
【解决方案2】:

听起来很疯狂,但您实际上可以嵌套这些异步方法:

async.series([
  function (done) {
    async.waterfall(readCommands, done);
  },
  function (done) {
    async.waterfall(writeCommands, done);
  }
], function (err) {
  // All done
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多