我让这个片段可以使用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做firstThing或.series(),但不确定我是需要_.pipeline还是.series()还是什么。
发布于 2014-08-11 16:13:22
目前还没有很好的1:1翻译,因为高地缺少一个“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-11-22 00:14:36
在我自己放弃异步到高地的尝试中,我开始有规律地使用.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)添加到高地的一个理由。
https://stackoverflow.com/questions/25230224
复制相似问题