DEV Community

Cover image for Introducing Async Channels
Eyal Shalev
Eyal Shalev

Posted on

2

Introducing Async Channels

What?

Channels are queue-like objects (First In First Out) that their enqueue (send) and dequeue (get) functions are asynchronous (async). By passing them between asynchronous functions we can synchronize operations between said functions.

Why?

Let's say we want to process a large chunk of data (simulated by a several lorem-ipsum paragraphs).
Some of the processes that we want to perform on that data are fast, while other are time (and resource) consuming.
To avoid overwhelming our infrastructure, we want to make not to send data to a process that isn't ready to accept new data. In other words, we want to implement back-preasure.
This is where Async Channels come into play.

When you send (or get) a message to (or from) a channel, it returns a promise.
For send requests, it will resolve if the channel has available buffer, or (if not), after a get is performed on the channel.
And on the opposite side, a get request will resolve if there is buffered message on the channel, or after a send request is made.

How?

Below is an example usage of async_channels, where long processes are simulated by calling sleep (a helper function that returns a promise that is resolved after n seconds).




You can view the documentation on eyal-shalev.github.io/async_channels

GitHub logo Eyal-Shalev / async_channels

Inspired by Go & Clojure Channels, async_channels provides channels as an asynchronous communication method between asynchronous functions.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay