highland.js异步数组到值流

highland.js async array to stream of values

本文关键字:数组 js 异步 highland      更新时间:2023-11-23

我正试图让以下片段返回相同的输出-数组值流。

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

第二个方法获得一个解析数组的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]

在这两种情况下,您都不需要调用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