rust / intermediate
Snippet
Async/Await with Futures 0.1 Representation
Rust's async/await syntax builds on the Future trait. A Future represents a value that may not be available yet. The poll method is called by the executor to check if the async operation has completed. When not ready, the waker must be registered to notify the executor later.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::future::Future;use std::task::{Poll, Context};use std::pin::Pin;struct DelayFuture {remaining: u32,}impl Future for DelayFuture {type Output = &'static str;fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {if self.remaining > 0 {self.remaining -= 1;println!("Polled {} times, still waiting...", 3 - self.remaining);cx.waker().wake_by_ref();Poll::Pending} else {Poll::Ready("Done waiting!")}}}async fn delayed_greeting() -> String {let future = DelayFuture { remaining: 3 };let result = future.await;format!("Async result: {}", result)}fn main() {let future = delayed_greeting();println!("Created async future");let waker = std::task::WakeNone;}
Breakdown
1
struct DelayFuture { remaining: u32 }
Custom future type holds state for polling logic
2
fn poll(mut self: Pin<&mut Self>, cx: &mut Context)
Poll receives pinned context and waker for notification
3
cx.waker().wake_by_ref()
Calling wake_by_ref schedules this future to be polled again
4
Poll::Pending
Returning Pending means operation not complete, executor should wait
5
Poll::Ready("Done waiting!")
Returning Ready with output indicates future has completed