• Returns a coroutine that waits for the first coroutine of coros to complete.

    When waited on with yield* returns the value returned by the first completed coroutine. All other coroutines are cancelled with Generator.return, triggering their finally handlers if any.

    Type Parameters

    • T

      Return type of all coros and as a result this coroutine

    Parameters

    • Rest ...coros: Coroutine<T>[]

      The coroutines to wait for

    Returns Generator<any, T, unknown>

    A generator that returns the value returned by first completed coroutine

    See

    Generator.return

    Example: Interrupt infinite coroutine

    import * as coro from '@ajeeb/coroutines'

    function* printForever(message) {
    while(true) {
    console.log(message)
    yield* seconds(1)
    }
    }

    function* waitForClick() {
    let pressed = false
    const button = document.querySelector("button")
    button.onclick = () => pressed = true
    while(!pressed) yield
    }

    const SCHED = new coro.Schedule()
    SCHED.add(coro.first(printForever("ping"), waitForClick()))
    setInterval(SCHED.tick, 100)

    Example: Get first pressed button

    import * as coro from '@ajeeb/coroutines'

    function* waitForClick(button) {
    let pressed = false
    button.onclick = () => pressed = true
    while(!pressed) yield
    return button.textContent
    }

    const buttons = Array.prototype.slice.call(document.querySelectorAll("button"))
    const SCHED = new coro.Schedule()
    SCHED.add(function* () {
    console.log("waiting for button press...")
    const pressedText = yield* coro.first(...buttons.map(waitForClick))
    console.log("pressed", pressedText)
    })
    setInterval(SCHED.tick, 100)