Rook
РусскийRU
// Async tasks share a thread: the waits interleave, but no new rook appears.
async func load(name string, delay number) string {
<-after(delay)
return name
}
const first = load("first", 30)
const second = load("second", 10)
console.log(await first, await second)
move 9 of 9 · 1–0

Every result is received. The game is played.

Async functions

async func returns a Promise, and await waits for it. The result types are written as in any function, several of them too: an async func load() (string, error) returns Promise<(string, error)>, and await unpacks the values back. A module can await at the top level, and an event handler can be async: a change of state after await updates the markup. In the task board, async functions load the current tasks from storage and save changes over the network without blocking the interface.

// An async function returns a Promise of its results; await waits for it
async func sleep(ms number) {
    const done Promise<number> = new Promise(resolve => setTimeout(() => resolve(ms), ms))
    await done
}

async func loadUser(id number) (string, error) {
    await sleep(300) // as if over the network
    if id <= 0 {
        return "", error(`no user with id ${id}`)
    }
    return `user #${id}`, null
}

// await works at the top level of a module too
const name, err = await loadUser(7)
console.log(name, err)

const _, notFound = await loadUser(0)
console.log("error:", notFound?.message)

// An event handler can be async: the markup updates after await
comp Profile() {
    state text = "nobody yet"
    return <button onClick={async () => {
        text = "loading…"
        const user, failed = await loadUser(42)
        text = failed == null ? user : failed.message
    }}>{text}</button>
}

document.body.append(<Profile />)