Skip to main content
Module

x/async_channels/mod.ts>Channel#get

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

get 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.get()
  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.get()
  console.assert(val === "Hello world!")
  console.assert(ok === true)

Aborting a get 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.get(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.