Rook
РусскийRU
// Cancellation stops a goroutine and returns control to its caller.
async func work() number {
<-after(100)
return 1
}
const task = go work()
<-after(10)
cancel(task)
try {
await task
} catch {
console.log("cancelled")
}
move 7 of 7 · 1–0

Every result is received. The game is played.

Signals and cancellation

A server stops when the process manager tells it to, with a signal, and a request stops when its client goes, with an AbortSignal. Both become channels, so that select waits for them with the rest, as signal.Notify and the Done() of a context do in Go.

When the server stops, it can use the signal channel to begin a graceful shutdown: stop accepting task work, let background workers finish or stop, then close their channels and the server.

signal("SIGINT", "SIGTERM") is a channel that gets the name of each signal. While it listens, the signals do not end the process, and it keeps the program running until it is closed, as a tick does:

server.rk
import { createServer } from "node:http"

const stop = signal("SIGINT", "SIGTERM")
const server = createServer(handle).listen(8080)
console.log("stopping on", <-stop)
close(stop)
server.close()

done(request.signal) gets the reason of an AbortSignal when it aborts, and is closed then; abortSignal(stop) is an AbortSignal that aborts when the channel gets a value or is closed, for fetch(url, { signal }) and the other APIs that take one. Signals are of Node, and these two work in the browser too:

// An AbortSignal as a channel: done() gets the reason when it aborts, and is closed
const controller = new AbortController()
setTimeout(() => controller.abort("the user left"), 100)

select {
case reason = <-done(controller.signal):
    console.log("cancelled:", reason)
case <-after(1000):
    console.log("finished")
}

// And a channel as an AbortSignal, for fetch(url, { signal }): it aborts when stop is closed
const stop = chan<bool>()
const aborting = abortSignal(stop)
aborting.addEventListener("abort", () => console.log("aborted:", aborting.aborted))
close(stop)