This package is my humble attempt to provide a Chan<T>
class for TypeScript, which would be as much as possible similar to Go's chan T
type.
npm install @harnyk/chan
See the tests and examples for more information.
Brief reference:
Go equivalent | TypeScript | |
---|---|---|
Create a channel of `number` with no buffer: |
ch := make(chan int) |
const ch = new Chan<number>(); |
Create a channel of `number` with fixed-size buffer: |
ch := make(chan int, 5) |
const ch = new Chan<number>(5); |
Iterate over `Chan` with `for await` |
for v := range ch {
fmt.Println(v)
} |
for await (const v of ch) {
console.log(v);
} |
Send a value to `Chan` with `send` |
ch <- 42 |
await ch.send(42); |
Receive a value from `Chan` with `recv` |
v, ok := <-ch |
const [v, ok] = await ch.recv(); |
Close `Chan` |
close(ch) |
ch.close(); |
Select over multiple channels |
select {
case ch <- 42:
fmt.Println("sent")
case v := <-ch1:
fmt.Printf("Received %d\n", v)
default:
fmt.Println("default")
} |
await select()
.send(ch, 42, () => console.log('sent'))
.recv(ch1, (v) => console.log(`Received ${v}`))
.default(() => console.log('default')); |
- asynchronous iterating over
Chan<T>
withfor await
- asynchronous
send
andrecv
select
-ing over multiple channels
WTFPL
Mark Harnyk (https://github.com/harnyk)