首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >async.applyEachSeries转换为highland.js

async.applyEachSeries转换为highland.js
EN

Stack Overflow用户
提问于 2014-08-10 15:41:43
回答 2查看 391关注 0票数 1

我让这个片段可以使用async.applyEachSeries很好地工作。

代码语言:javascript
复制
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()还是什么。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-11 16:13:22

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

代码语言:javascript
复制
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
  });
票数 3
EN

Stack Overflow用户

发布于 2014-11-22 00:14:36

在我自己放弃异步到高地的尝试中,我开始有规律地使用.map(_.wrapCallback).invoke('call')。我们可以在这里使用它:

代码语言:javascript
复制
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参数:

代码语言:javascript
复制
_([firstThing.bind(firstThing, state),
  secondThing.bind(secondThing, state)])
  .map(_.wrapCallback)
  .invoke('call')
  .series().toArray(function() {
    console.log(state)
  });

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

最后,必须在最后使用.toArray感觉很奇怪,尽管这可能只是将.done(cb)添加到高地的一个理由。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25230224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档