async
Task spawning, async channels, and combinators for concurrent programming.
Import
import asyncFunctions
async.spawn(fn: () -> any) -> task
Run a function as an async task, returning a task handle.
async.sleep(secs: float)
Async sleep that yields control to other tasks.
async.channel() -> channel
Create an unbounded channel for passing values between tasks.
async.select(channels: [channel]) -> any
Poll multiple channels and return the value from whichever is ready first.
async.all(tasks: [task]) -> [any]
Wait for all tasks to complete and return an array of their results.
async.race(tasks: [task]) -> any
Return the result of whichever task completes first.
async.resolve(val: any) -> task
Create an already-resolved task with the given value.
async.reject(err: any) -> task
Create an already-rejected task with the given error.
Examples
import async
-- spawn two tasks and wait for both
let t1 = async.spawn(fn() {
async.sleep(0.1)
return "first"
})
let t2 = async.spawn(fn() {
async.sleep(0.05)
return "second"
})
let results = async.all([t1, t2])
println(results) -- [first, second]
-- race: first to finish wins
let winner = async.race([t1, t2])
println(winner)
-- channel
let ch = async.channel()
async.spawn(fn() { ch.send("hello") })
println(ch.recv()) -- hello