1

我使用async.applyEachSeries.

var async = require("async");

function firstThing(state, next) {
  state.firstThingDone = true;
  setImmediate(next);
}

function secondThing(state, next) {
  state.secondThingDone = true;
  setImmediate(next);
}

var state = {};
async.applyEachSeries([
  firstThing,
  secondThing
], state, function (error) {
  console.log(error, state);
});

我已经多次尝试将其转换为 highland.js,但我并没有摸索那里的管道。我很确定我需要_.wrapCallback(firstThing)为 firstThing 和 secondThing 做,但不确定我是否需要_.pipeline.series()什么。

4

2 回答 2

3

目前还没有很好的 1:1 翻译,因为 Highland 缺少“applyEach”,但是通过更改(或包装)firstThing 和 lastThing 函数,您可能会得到足够好的结果:

var _ = require('highland');

/**
 * These functions now return the state object,
 * and are wrapped with _.wrapCallback
 */

var firstThing = _.wrapCallback(function (state, next) {
  state.firstThingDone = true;
  setImmediate(function () {
    next(null, state);
  });
});

var secondThing = _.wrapCallback(function (state, next) {
  state.secondThingDone = true;
  setImmediate(function () {
    next(null, state);
  });
});

var state = {};

_([state])
  .flatMap(firstThing)
  .flatMap(secondThing)
  .apply(function (state) {
    // updated state
  });
于 2014-08-11T16:13:22.490 回答
1

在我自己为 Highland 放弃 async 的尝试中,我已经习惯.map(_.wrapCallback).invoke('call')性地使用它。我们可以在这里使用它:

var _ = require('highland');

var state = {};

function firstThing(state, next) {
  state.firstThingDone = true;
  setImmediate(next);
}

function secondThing(state, next) {
  state.secondThingDone = true;
  setImmediate(next);
}

_([firstThing, secondThing])
  .map(_.wrapCallback)
  .invoke('call', [null, state])
  .series().toArray(function() {
    console.log(state)
  });

这让我们可以保持您的功能原样,它很好地扩展到两个以上的“事物”,我认为它更像是对 applyEachSeries 的直接分解。

如果我们需要为this每个函数绑定或传递不同的参数,我们可以.bind在构造流时使用并省略call参数:

_([firstThing.bind(firstThing, state),
  secondThing.bind(secondThing, state)])
  .map(_.wrapCallback)
  .invoke('call')
  .series().toArray(function() {
    console.log(state)
  });

另一方面,这种方法的副作用更大。我们流中的东西不再是我们最终要转换和利用的东西。

最后,不得不.toArray在最后使用感觉很奇怪,尽管这可能只是添加.done(cb)到 Highland 的一个论点。

于 2014-11-22T00:14:36.237 回答