Search code examples
javascriptreactive-programmingbluebirdhighland.js

Higland.js: wrap toCallback into promise


I want to write something like:

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

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

But I see an error:

TypeError: this.consume is not a function

How do I properly bind the context in the case


Solution

  • First problem is that .toCallback loses it's contests, so this is not a stream anymore and that's why this.consume is not a function.

    The easies way to solve is to wrap it with an arrow function.

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

    The second thing is that you cannot use toCallback with the steams emitting multiple values, because it'll throw an error. (Please check the docs)

    To fix it you could call .collect() like this:

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