0

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

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

第二种方法将解析数组的 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]
4

1 回答 1

2

在这两种情况下,您都不需要调用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
于 2016-10-13T17:56:30.747 回答