View profile

The Difference between Async Iterators and Observables

You can classify JavaScript code into two categories: imperative JavaScript and reactive JavaScript.
The Difference between Async Iterators and Observables
By Mastering JavaScript Tutorials • Issue #11 • View online
You can classify JavaScript code into two categories: imperative JavaScript and reactive JavaScript. Suppose you want to print a message whenever a user clicks on a div tag. Normally, you would just register a callback with the addEventListener function.

Reactive means responding to events without knowing where the events come from
Reactive means responding to events without knowing where the events come from
The event handler is an example of reactive JavaScript. The event handler runs in response to an event. It has no idea where the event came from, and it doesn’t have any influence on the code that emitted the event.
Writing this code in imperative style is possible, albeit more exotic. Here’s how you could write it in imperative style:
Promises and async/await wrap reactive code so you can use imperative style
Promises and async/await wrap reactive code so you can use imperative style
The for loop is an example of imperative JavaScript. Your code is explicitly responsible for awaiting the next click.
You might wonder whether imperative or reactive is better. The answer is that you need a little bit of both to write JavaScript effectively. Certain things are easier with reactive code, like listening to click events. Other things, like iterating through a Mongoose cursor, are easier with for loops and async/await (imperative), as opposed to callbacks (reactive).
Before promises and async/await, JavaScript was written primarily in a reactive way: callback hell. However, now we have the choice to write async code in a reactive way or an imperative way. Reactive code can get tangled and hard to read, but imperative code has its quirks. For example, what happens if the user clicks twice in rapid succession with the below code?
Clicking twice within 1 second means this code will miss an event
Clicking twice within 1 second means this code will miss an event
Async iterators are an imperative construct: the underlying async operation will not proceed until you explicitly call the next() function. RxJS observables are reactive: RxJS executes your code in response to events, but you have no control over the events.
This Week's Tutorials
Did you enjoy this issue?
Mastering JavaScript Tutorials

Mastering JavaScript Tutorials

If you don't want these updates anymore, please unsubscribe here
If you were forwarded this newsletter and you like it, you can subscribe here
Powered by Revue