2016-04-01 28 views
0

我想要得到以下代码片段来返回相同的输出 - 数组值的流。highland.js异步数组到数据流

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

第二种方法获取解析数组的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] 
+1

您在第一种情况下使用的每个,而不是在第二个。 – Shanoor

回答

2

在你不需要调用done这两种情况下,因为each已经消耗你流。

承诺的情况会将解析后的值(即数字数组)传递到流中。您可以使用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