我使用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,但我并没有在那里找到管道。我非常确定我需要为firstThing和secondThing _.wrapCallback(firstThing)
做_.pipeline
但不确定我是否需要.series()
或{{1}}或者是什么。
答案 0 :(得分: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
});
答案 1 :(得分:1)
在我自己试图放弃对高地的异步时,我已经开始有条理地使用.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)
添加到高地的论据。