Async work
Keep the window responsive while waiting: async handlers, tasks with loading and error states, background threads and cancellation.
janelkit Included with janelkit. Nothing extra to install. What you will learn
- Why waiting must not block the interface thread.
- How async handlers and @task keep the window responsive.
- How to run blocking code in background, and what workers may not touch.
- What cancellation does, and what it cannot undo.
Waiting is not the same as blocking
The window can only repaint and react to clicks while its thread is free. A function that sleeps, downloads or reads a large file on that thread freezes the whole window until it finishes.
async def lets a function wait without blocking: at each await, the thread is free to do other work, and the function continues later. JanelKit runs asyncio on Qt’s event loop (through qasync), so coroutines run on the interface thread and can change state directly after an await. Async does not mean another thread: code between awaits still runs on the interface thread, so a long calculation inside async def still freezes the window. For that, use background.
| Your situation | Use |
|---|---|
| A library with async functions (httpx, aiohttp…) | An async def handler that awaits it. |
| Loading and error states shown on screen | @task, with .loading, .error and .value. |
| A blocking function (requests, file I/O, heavy CPU) | await background(fn, ...) inside async code. |
| Start something without waiting for it | spawn(coroutine). |
| Repeat something, or do it later | interval and timeout (see Timers). |
Common mistakes
- Adding async to a function does not make the blocking code inside it non-blocking.
- Never call asyncio.run or time.sleep in a handler: the application already runs the event loop, and sleeping blocks it.
An async event handler
Any handler can be async def. JanelKit starts the coroutine for you when the event happens, so the template does not change. Errors are logged with the handler’s location. This example waits with asyncio.sleep instead of calling a real service, so it runs anywhere.
<script lang="python">
import asyncio
from janelkit import state
busy = state(False)
message = state("Ready")
async def save():
busy.value = True
try:
message.value = "Saving…"
await asyncio.sleep(0.5) # stands in for a real save
message.value = "Saved"
finally:
busy.value = False
</script>
<column padding={24} gap={12}>
<button enabled={not busy} on:click={save}>Save</button>
<text>{message}</text>
</column>CopyComplete component · Save as src/App.janel in a scaffolded project.
How it works
- busy disables the button while a save is in progress, so it cannot start twice.
- While save is waiting, the window keeps responding.
- finally clears busy even if the save fails or is cancelled.
What you should see
Save shows Saving… and disables the button; half a second later it shows Saved and the button is enabled again.
@task: loading, error and result for the screen
@task turns an async function into a Task object with three reactive properties the template can show: loading, error and value. task.run(...) starts it, cancelling any previous run that is still going; task.cancel() stops it. The decorator does not start anything by itself.
While a new run loads, the previous successful value is kept. A failure stores the exception in error and keeps the old value; you decide what to show.
<script lang="python">
import asyncio
from janelkit import state, task
query = state("Ada")
@task
async def lookup(text):
await asyncio.sleep(0.3)
if not text.strip():
raise ValueError("Enter a name")
return "Hello, " + text.strip()
</script>
<column padding={24} gap={12}>
<textfield bind:value={query} label="Name" />
<row gap={8}>
<button on:click={lookup.run(query)}>Look up</button>
<button on:click={lookup.cancel()}>Cancel</button>
</row>
{#if lookup.loading}
<text>Loading…</text>
{:else if lookup.error is not None}
<text>Error: {lookup.error}</text>
{:else}
<text>{lookup.value or "No result yet"}</text>
{/if}
</column>CopyComplete component · Save as src/App.janel in a scaffolded project.
How it works
- lookup.run(query) starts a run with the current text; the {#if} chain shows its state.
- Raising an exception is the normal way to report a failure: it ends up in lookup.error.
- Clicking Look up again while loading cancels the previous run before starting a new one.
What you should see
Look up shows Loading… and then Hello, Ada. Emptying the field and looking up again shows Error: Enter a name.
background: run blocking code in another thread
await background(fn, *args) runs an ordinary function in a worker thread and gives you its result. Use it for libraries without async support, file access and heavy calculations. The worker must not touch state or the interface: read what you need first, pass it as arguments, and assign the result after the await, back on the interface thread.
<script lang="python">
import time
from janelkit import state, task, background
name = state("Ada")
def slow_upper(text): # an ordinary blocking function
time.sleep(0.3)
return text.upper()
@task
async def formatted(text):
return await background(slow_upper, text)
</script>
<column padding={24} gap={12}>
<textfield bind:value={name} label="Name" />
<button on:click={formatted.run(name)}>Format</button>
<text>{"Working…" if formatted.loading else formatted.value or ""}</text>
</column>CopyComplete component · Save as src/App.janel in a scaffolded project.
How it works
- slow_upper knows nothing about JanelKit: it receives a string and returns a string.
- background runs it in a worker, so the window keeps responding during the sleep.
- The result returns to the interface thread and becomes formatted.value.
What you should see
Format shows Working… and then ADA, and the window keeps responding meanwhile.
Common mistakes
- Writing state from a worker raises a wrong-thread error. Return the data instead.
- Do not pass a reactive list to a worker to change it; pass a plain copy.
Cancellation stops the waiting, not the world
Cancelling a task, or destroying the component that owns it, delivers CancelledError at the next await. Let it propagate; use finally for small cleanups. A worker thread started by background cannot be stopped: it runs to the end, but its result is discarded. Cancellation is not a rollback: a request already sent to a server may still take effect.
Common mistakes
- Do not catch BaseException or CancelledError to carry on as if nothing happened.
- A task does not restart when its input state changes; call run again with the new input.
spawn: start work without waiting for it
spawn(coroutine) starts a coroutine and returns immediately, for example to load data when a component mounts. When called during setup, in a synchronous handler or in on_mount, the work belongs to the component and is cancelled if the component is destroyed first. Errors are logged, or passed to spawn(coroutine, on_error=fn).
<script lang="python">
import asyncio
from janelkit import state, on_mount, spawn
message = state("Loading…")
async def load():
await asyncio.sleep(0.3)
message.value = "Ready"
@on_mount
def start():
spawn(load())
</script>
<text>{message}</text>CopyComplete component · Save as src/App.janel in a scaffolded project.
What you should see
Loading… appears first and changes to Ready.
Common mistakes
- Create long-lived tasks and timers during setup. Work created after an await is not automatically owned by the component.
Test the waiting
In tests, app.wait(until=condition, timeout=2) runs the event loop until the condition holds, and fails with InspectError if the timeout passes first; app.wait(seconds) just runs it for that long. A plain time.sleep in a test would block the very loop that should finish the work. Test the success path, the error path and cancellation separately.
# tests/test_lookup.py, for the @task example above saved as src/App.janel
from janelkit.inspect import mount
def test_lookup():
with mount("src/App.janel") as app:
lookup = app.get("lookup")
app.find(text="Look up").click()
assert lookup.loading
app.wait(until=lambda: not lookup.loading, timeout=2)
assert lookup.value == "Hello, Ada"CopyLearn moreTesting your application ↗Timers ↗
Key points
- Never block the interface thread: await async work, run blocking code in background.
- @task gives the screen loading, error and value; run starts it, cancel stops it.
- Work started by a component is cancelled with it; cancellation does not undo side effects.
English documentation based on the JanelKit source. For additional details, browse the source docs ↗.