【问题标题】:highland.js async array to stream of valueshighland.js 异步数组到值流
【发布时间】:2016-04-01 14:08:06
【问题描述】:

我正在尝试让以下 sn-ps 返回相同的输出 - 数组值流。

第一个方法从一个数组开始并发出值。

第二种方法获取一个解析数组的promise作为输入,因此它不会发出每个值,而是只发出数组本身。

我应该在第二种方法中更改什么以使其输出与第一种相同的内容?

const h = require('highland');

var getAsync = function () {
  return new Promise((resolve, reject) => {
    resolve([1,2,3,4,5]);
  });
}

h([1,2,3,4,5])
  .each(console.log)
  .tap(x => console.log('>>', x))
  .done();
 //outputs 5 values, 1,2,3,4,5


h(getAsync())
  .tap(x => console.log('>>', x))
  .done();
//outputs >>[1,2,3,4,5]

【问题讨论】:

  • 你在第一种情况下使用了每个,而不是在第二种情况下。

标签: javascript node.js stream highland.js


【解决方案1】:

在这两种情况下,您都不需要调用 done,因为 each 已经在使用您的流。

promise 的情况会将解析后的值(即一个数字数组)向下传递。您可以使用series 方法将此流中的每个数组转换为它自己的流,然后连接流。在这个例子中这有点违反直觉,因为只有一个数组,因此只有一个要连接的流。但这就是你想要的 - 一个数字流。

代码如下:

const h = require('highland');

var getAsync = function () {
  return new Promise((resolve, reject) => {
    resolve([1,2,3,4,5]);
  });
}

h([1,2,3,4,5])                      // stream of five numbers
  .each(console.log)                // consumption

h(getAsync())                       // stream of one array
  .series()                         // stream of five numbers
  .each(x => console.log('>>', x))  // consumption

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 2014-10-27
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2013-07-12
    相关资源
    最近更新 更多