Skip to main content
Module

x/async_channels/mod.ts>Receiver

Inspired by Go & Clojure Channels, async_channels provides channels as an asynchronous communication method between asynchronous functions.
Go to Latest
interface Receiver
implements AsyncIterable<T>
Re-export
import { type Receiver } from "https://deno.land/x/async_channels@v1.0.0-alpha45/mod.ts";

Type Parameters

T

The type of value that can be received.

Methods

receive(abortCtrl?: AbortController): Promise<[T, true] | [undefined, false]>

Receive returns a promise that will be resolved with [T, true] when a value is available, or rejected if a provided AbortController is aborted

If the channel is closed, then the promise will be resolved immediately with [undefined, false].

Receiving from a closed channel:

  import {Channel} from "./channel.ts";
  const ch = new Channel();
  ch.close();
  const [val, ok] = await ch.receive()
  console.assert(val === undefined)
  console.assert(ok === false)

Receiving from a buffered channel:

  import {Channel} from "./channel.ts";
  const ch = new Channel(1);
  await ch.send("Hello world!")
  ch.close();
  const [val, ok] = await ch.receive()
  console.assert(val === "Hello world!")
  console.assert(ok === true)

Aborting a receive request:

  import {Channel, AbortedError} from "./channel.ts";
  const ch = new Channel(1);
  await ch.send("Hello world!")
  ch.close();
  const abortCtrl = new AbortController()
  abortCtrl.abort()
  try {
    await ch.receive(abortCtrl);
    console.assert(false, "unreachable");
  } catch (e) {
    console.assert(e instanceof AbortedError);
  }
[[Symbol.asyncIterator]](): AsyncGenerator<T, void, void>

Creates an AsyncGenerator that yields all values sent to this channel, and returns when the channel closes.

map<TOut>(
fn: (val: T) => TOut | Promise<TOut>,
bufferSize?: number,
): Receiver<TOut>

map returns a receiver channel that contains the results of applying fn to each value of this channel.

The receiver channel will close, when the original channel closes.

flatMap<TOut>(
fn: (val: T) => Iterable<TOut> | AsyncIterable<TOut>,
bufferSize?: number,
): Receiver<TOut>
forEach(
fn: (val: T) => void | Promise<void>,
bufferSize?: number,
): Receiver<void>

forEach applies fn to each value in this channel, and returns a channel that will close after this channel closes.

filter(
fn: (val: T) => boolean | Promise<boolean>,
bufferSize?: number,
): Receiver<T>
reduce(
fn: (prev: T, current: T) => T | Promise<T>,
bufferSize?: number,
): Receiver<T>