async-deferred
A lightweight utility for fire-and-forget async computations in Rust. Start asynchronous tasks immediately and retrieve their results later without blocking. Works with any async runtime.
Features
- Fire-and-forget pattern: start computations without waiting for results
- Deferred retrieval: check results when convenient using non-blocking operations
- Panic handling: detect if the task or its callback panicked, and why
- Callback support: run code with the result as soon as the task finishes
- Cancellation: stop a running task and reuse the
Deferred - Any runtime: Tokio by default, smol behind a feature, or your own through the
Spawnertrait no_std: works on embedded executors such as embassy, with a heap allocator
The result type only needs to be Send + 'static, the same as tokio::spawn.
Examples
Non-blocking Result Checking
use Deferred;
use Duration;
use sleep;
async
With Completion Callbacks
use Deferred;
async
Await for a result
use Deferred;
use Duration;
use sleep;
async
Error Handling
use ;
async
Cancellation
use ;
async
Runtimes
Tasks are started through a spawner, which hands them to an async runtime.
| Feature | Spawner | Notes |
|---|---|---|
tokio (default) |
Tokio, tokio::runtime::Handle |
Enables the start and begin shortcuts used above |
smol |
Smol, smol::Executor<'static> |
|
std (default) |
Catches panics in the task and callback. Without it, the crate is no_std + alloc |
To use another runtime without pulling in Tokio:
= { = "0.3", = false, = ["smol"] }
smol
use ;
Your own runtime
Any runtime works by implementing Spawner:
use Future;
use ;
;
let mut deferred = start_on;
For single-threaded executors and futures that are not Send, implement LocalSpawner
and use the *_local_on methods.
Embassy (no_std)
= { = "0.3", = false }
embassy_spawner! declares a spawner for embassy in one line. You also need a heap allocator,
such as esp-alloc or embedded-alloc, and a target with atomic compare-and-swap.
use ;
use ;
// Lets up to 4 `Deferred` tasks run at the same time.
embassy_spawner!;
async
The futures can hold values that are not Send, such as Rc or peripheral drivers.
Starting more than pool_size tasks at the same time panics.
Without the std feature, panics are not caught, so TaskPanicked and CallbackPanicked
are never reported. On embedded targets a panic usually halts the device anyway.
A complete example for the ESP32-S3, with tests that run on the chip, is in
embassy-esp32s3/.
License
Licensed under the MIT license.