Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/easyts/mod.ts>Chan

js library written with ts, use select and chan like golang in js.
Latest
class Chan
implements ReadChannel<T>, WriteChannel<T>
import { Chan } from "https://deno.land/x/easyts@0.1.3/mod.ts";

The concrete realization of Channel

Examples

use

function sum(s: Array<number>, c: WriteChannel<number>) {
    let sum = 0
    for (const v of s) {
        sum += v
    }
    c.write(sum) // send sum to c
}
async function main() {
    const s = [7, 2, 8, -9, 4, 0]
    const c = new Chan<number>()
    sum(s.slice(0, s.length / 2), c)
    sum(s.slice(s.length / 2), c)

    const [x, y] = [await c.read(), await c.read()] // receive from c

    console.log(x, y, x + y)
}
main()

buffered

    const ch = new Chan<number>(2)
    ch.write(1)
    ch.write(2)
    let [v,ok]= ch.readRaw()
    console.log(v,ok)
    v = ch.read()
    console.log(v)

Constructors

new
Chan(buf?)

Properties

private
rw_: RW<T>

Low-level read and write implementation

readonly
capacity: number

Returns how much data the channel has buffered

readonly
isClosed: boolean

Returns whether the channel is closed

readonly
length: number

Returns the channel buffer size

readonly
rw: RW<T>

Methods

close(): boolean

Close the channel, after which the channel will not be able to write, all blocked reads and writes are returned, but the value that has been written to the channel is guaranteed to be fully read

Read a value from the channel, block if there is no value to read, and return until there is a value or the channel is closed

Create a case for select to read

Read a value from the channel, block if there is no value to read, and return until there is a value or the channel is closed

tryRead(): IteratorResult<T> | undefined

Attempts to read a value from the channel, returns undefined if no value is readable, returns {done:true} if the channel is closed

tryWrite(val: T, exception?: boolean): boolean

Attempt to write a value to the channel

wait(): undefined | Promise<void>

Wait for chan to close, no data will be read from chan

write(val: T, exception?: boolean): boolean | Promise<boolean>

Writes a value to the channel, blocking if the channel is not writable until the channel is writable or closed

writeCase(val: T, exception?: boolean): WriteCase<T>

Create a case for select to write to

[Symbol.asyncIterator](): AsyncGenerator<T>

Implement asynchronous iterators

Static Properties

private
closed_: undefined | Chan<any>
private
never_: undefined | Chan<any>
readonly
closed: Chan<any>

Returns a alreay closed chan, usually used as some token

readonly
never: ReadChannel<any>

Returns a chan that will never have a value, usually used as some token