2017-01-13 62 views
1

我想寫類似:Higland.js:包裝toCallback到承諾

const Promise = require('bluebird') 
const H = require('highland') 

Promise.fromCallback(
    H([1, 2, 3]).toCallback 
).then(function(val) { 
    expect(val).eql(1, 2, 3) 
}) 

但我看到了一個錯誤:

TypeError: this.consume is not a function 

如何正確結合上下文的情況下

回答

1

第一個問題是.toCallback丟失了比賽,所以this不再是流,因此this.consume不是一個函數。

easies解決方法是用箭頭函數包裝它。

cb => H([1, 2, 3]).toCallback(cb) 

第二件事是你不能使用toCallback發射多個值的蒸​​汽,因爲它會引發錯誤。 (請the docs

要解決它,你可以調用.collect()這樣的:

const Promise = require('bluebird'); 
 
const H = require('highland'); 
 
const assert = require('assert'); 
 

 
Promise.fromCallback(
 
\t cb => H([1, 2, 3]).collect().toCallback(cb) 
 
).then(function(val) { 
 
\t assert.deepEqual(val, [1, 2, 3]); 
 
\t console.log('All good.'); 
 
});

+0

很酷的答案,THX! – kharandziuk