caolan/highland

How to extract the result from reduce()

Opened this issue · 2 comments

How do I reliably extract the final value from a reduce operation

eg
let numItems = -1
_([1, 2, 3]).reduce(0, (acc, value) => acc + 1).each(x => numItems = x)

This works for this simple example but for a more complex situation where the stream is a file that is split into lines its tricky.

At the nodejs command line it works but running in a test harness numItems is -1. I'm thinking that the stream hasn't finished reading the lines by the time I check the value.

How do I wait for it to finish before checking

vqvu commented

Highland streams are generally asynchronous. That's why your code doesn't always work. The fact that this code works in the command line is a coincidence and a side effect of how the stream is implemented.

I'm not sure what test harness you are using, but you need to use its support for asynchronous tests.

For example, in Highland's own tests, we use nodeunit, which provides a test object with assert and done methods that can be called asynchronously. Then we run the actual assertions within the each or toArray callback. See this code for an example: https://github.com/caolan/highland/blob/2.13.0/test/test.js#L3172

If you harness uses Promises to handle asynchronous tests, you can also use toPromise.

Thanks vqku, I'm using Mocha as my test framework, it has similar support for asynchronous tests so I'll amend my tests .