select
select waits for the first of several operations on channels and runs its case, as in Go: case text = <-fast: receives into a new variable of the case, case out <- v: sends, and default runs when nothing is ready at once. after(ms) is a channel that gets the time once, after ms, so it makes a timeout, and a case whose channel is null never goes on.
// select waits for the first of several operations on channels; // after(ms) is a channel that gets the time once, after ms // out chan<- string only sends: search cannot receive from it async func search(query string, ms number, out chan<- string) { <-after(ms) // as if over the network out <- `results for "${query}" in ${ms} ms` close(out) // one answer, and nothing more } // Waiting needs no other thread: an async call without await runs in this thread. // Room for one answer: a search that nobody waits for can still finish const fast = chan<string>(1) const slow = chan<string>(1) search("guava", 100, fast) search("papaya", 2000, slow) // The first answer wins select { case text = <-fast: console.log(text) case text = <-slow: console.log(text) } // A timeout stops waiting select { case text = <-slow: console.log(text) case <-after(500): console.log("timeout: 500 ms") } // default runs when nothing is ready at once select { case text = <-slow: console.log(text) default: console.log("slow is not ready yet") } // A null channel turns its case off: each search is waited for once let lime ?chan string = chan<string>(1) let kiwi ?chan string = chan<string>(1) search("lime", 80, lime) search("kiwi", 40, kiwi) for lime != null || kiwi != null { select { case text = <-lime: console.log(text) lime = null case text = <-kiwi: console.log(text) kiwi = null } }
The board's worker can use select to choose between its next task command and a timeout. It can respond to work as soon as a command arrives, but still wake periodically when the queue stays quiet.
tick(ms) gets the time every ms until close(ticks). cancel(task) stops a goroutine, given the Promise of go: it stops at once, even in the middle of a loop, and the Promise fails with "goroutine cancelled".
// tick(ms) gets the time every ms until it is closed; cancel(task) stops a goroutine func countPrimes(limit number) number { let count = 0 for let n = 2; n < limit; n++ { let prime = true for let d = 2; d * d <= n; d++ { if n % d == 0 { prime = false break } } if prime { count++ } } return count } const ticks = tick(100) const done = chan<number>(1) const task = go async func() { done <- countPrimes(100_000_000) close(done) // the only value: nothing more is sent }() const timeout = after(450) let waiting = true for waiting { select { case n = <-done: console.log("primes:", n) waiting = false case <-ticks: console.log("still counting") case <-timeout: // The goroutine stops at once, even in the middle of a loop cancel(task) console.log("too slow: cancelled") waiting = false } } close(ticks) try { await task } catch e { console.log(e.message) }