Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to extract the result from reduce() #648

Open
Systemrate opened this issue Jun 5, 2018 · 2 comments
Open

How to extract the result from reduce() #648

Systemrate opened this issue Jun 5, 2018 · 2 comments

Comments

@Systemrate
Copy link

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
Copy link
Collaborator

vqvu commented Jun 5, 2018

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.

@Systemrate
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants