RxJS Functions (Part 2)

Corey Pyle
3 min readJan 9, 2019

--

bindNodeCallback

One thing I’m really growing to love about ReactiveX is the shear number of functions that exist in the API. It’s kind of like lodash for Observables. Often I’ll find myself trying to use two or three of the functions I’m familiar with only to discover later that a single function in the API already does what I need.

Previously, I posted an example of bindCallback which takes a standard function that uses a callback, and converts it into an Observable. If you’re accustomed to NodeJS however, you may have noticed that bindCallback is not well suited to handle the Node (error, result) => {} callback structure. bindNodeCallback illustrates well the sugary-ness of RxJS mentioned above.

bindNodeCallback

It’s just like bindCallback, but the callback is expected to be of type callback(error, result).

Like the description above from the docs says, bindNodeCallback is the same as bindCallback. The only difference is that you would use bindNodeCallback when the signature of your callback function matches that of NodeJS’s. Let’s look at our previous example of a function which takes a callback:

When the click event is fired, the listener we setup with addEventListener will call the function onClick and pass it the value of the click event. So the function signature would be (event) => {}.

However, in NodeJS, the standard callback function signature in this scenario would be something like (error, event) => {}. If any error is thrown during the execution of the function using our callback, it will pass the error to the callback.

Let’s try to use bindCallback on a function using a callback with this type of signature and see what happens:

When this code is run you’ll see that an Error object is logged normally to the console. The error was passed to the next function instead of the err function. Why? Because bindCallback assumes that the first argument passed to the callback (in this case the ‘Oh no!’ error) is a normal value. That’s where bindNodeCallback comes in:

Now when we run the code, we see an error output to the console as expected. The only difference is that bindNodeCallback was used instead bindCallback. The first argument passed to the callback is truthy, so the err function is called on our observer instead of the next function.

Note: Like bindCallback, bindNodeCallback also completes after it emits once.

While bindNodeCallback is definitely useful, the name is a little wanting. The error first callback syntax is just a convention. It could be used anywhere, and not just node. Maybe bindErrorFirstCallback?

Stay tuned for Part 3. Things will start getting more interesting now as the next couple of functions deal with manipulating the data streams themselves instead of just creating them. And be sure to check out Part 1.

--

--