Skip to main content
The Deno 2 Release Candidate is here
Learn more
Module

x/async_channels/channel.ts>Channel#receive

Inspired by Go & Clojure Channels, async_channels provides channels as an asynchronous communication method between asynchronous functions.
Go to Latest
method Channel.prototype.receive
import { Channel } from "https://deno.land/x/async_channels@v1.0.0-alpha54/channel.ts";

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);
  }

Parameters

optional
abortCtrl: AbortController

Returns

Promise<[T, true] | [undefined, false]>

will be resolved when message was passed, or rejected if abortCtrl was aborted or the channel is closed.