menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Technology News

>

Mastering ...
source image

Hackernoon

1M

read

357

img
dot

Image Credit: Hackernoon

Mastering Effect Programming in JavaScript with Generators and Deno

  • In this article, the author explores how to implement generators through a simple web application using Deno with TypeScript. Deno is a runtime environment for executing TypeScript and JavaScript code, serving as an alternative to Node.js. The web application will be a chatbot that can report the current time, add numbers, and interact with multiple users simultaneously. It will use WebSocket to receive messages from users and respond using a channel and generators. This approach provides a compact and readable representation of business logic and convenient decomposition while isolating dialogues and ensuring encapsulation of business logic.
  • The author uses an HTTP server with WebSocket support in Deno, which does not require specialized libraries. A channel is used to represent our entire dialogue with users and is implemented as a class named Channel.
  • Additionally, the article delves into 'generators,' with a focus on Asynchronous Iterators and the yield* operator. The author defines 'effect' as the entire dialogue with a user represented as a generator, yielding different effects at each step. The say effect is executed immediately, sending a message to the socket, and the generator's code continues without waiting for data from the external environment. At each step, the generator either sends a message to the socket or suspends execution until a message is received and immediately passed back to the generator.
  • The advantages of using generators include the conciseness, convenience of decomposition, simplicity of effects, and isolation of dialogues. Although this approach has a downside that the types of returned values from the yield operator are not automatically inferred. The code inside the generator is very abstract, and it represents pure business logic — a precise and noiseless description of business processes. It makes it easy to write tests for business logic by checking that the sequence of effects returned by the generator matches the expected sequence.

Read Full Article

like

21 Likes

For uninterrupted reading, download the app