await 关键字
核心概念
.await 是 Rust 中用于等待一个 Future 完成的关键字。它只能在 async 函数或 async 代码块中使用。当执行到 .await 时,如果 Future 尚未完成(返回 Pending),当前任务会被挂起,让出执行权给异步运行时,运行时可以去执行其他就绪的任务。等到 Future 完成(返回 Ready(value))时,.await 表达式的值就是 Future 的输出值,当前任务继续执行。这和线程的阻塞有本质区别——.await 不会阻塞线程,只是暂停当前异步任务。
use tokio::time::{sleep, Duration};
async fn fetch_data() -> String {
// .await 暂停当前任务,等待 sleep 完成
// 这期间线程可以执行其他任务
sleep(Duration::from_millis(100)).await;
"数据已获取".to_string()
}
#[tokio::main]
async fn main() {
// .await 等待 fetch_data 的 Future 完成
// 返回值是 Future 的 Output 类型(String)
let data = fetch_data().await;
println!("{}", data);
}await 的非阻塞特性
use tokio::time::{sleep, Duration, Instant};
async fn task(name: &str, ms: u64) -> String {
println!(" {} 开始", name);
sleep(Duration::from_millis(ms)).await;
// await 期间线程不被阻塞,可以执行其他任务
println!(" {} 完成", name);
format!("{}的结果", name)
}
#[tokio::main]
async fn main() {
// === 顺序 await:一个接一个等待 ===
let start = Instant::now();
println!("=== 顺序 await ===");
let r1 = task("任务A", 200).await;
let r2 = task("任务B", 200).await;
println!("{}, {}", r1, r2);
println!("顺序耗时: {:?}\n", start.elapsed()); // ~400ms
// === 并发 await:同时驱动多个 Future ===
let start = Instant::now();
println!("=== 并发 await (join!) ===");
let (r1, r2) = tokio::join!(
task("任务A", 200),
task("任务B", 200)
);
println!("{}, {}", r1, r2);
println!("并发耗时: {:?}", start.elapsed()); // ~200ms
// 关键区别:
// 顺序 await → 总时间 = 各任务时间之和
// join! → 总时间 = 最长任务的时间
}await 的链式调用
use tokio::time::{sleep, Duration};
async fn get_user_id(name: &str) -> u32 {
sleep(Duration::from_millis(50)).await;
match name {
"张三" => 1001,
"李四" => 1002,
_ => 0,
}
}
async fn get_user_email(id: u32) -> String {
sleep(Duration::from_millis(50)).await;
format!("user{}@example.com", id)
}
async fn send_email(email: &str, content: &str) -> bool {
sleep(Duration::from_millis(50)).await;
println!("发送邮件到 {}: {}", email, content);
true
}
#[tokio::main]
async fn main() {
// 链式 await:每一步依赖前一步的结果
let id = get_user_id("张三").await;
let email = get_user_email(id).await;
let sent = send_email(&email, "你好").await;
println!("发送结果: {}", sent);
// 可以直接在方法调用上 await
// 注意:.await 是后缀语法,放在表达式后面
let email = get_user_email(get_user_id("李四").await).await;
println!("李四的邮箱: {}", email);
}await 与错误处理
use tokio::time::{sleep, Duration};
#[derive(Debug)]
struct AppError(String);
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
async fn connect_db() -> Result<String, AppError> {
sleep(Duration::from_millis(50)).await;
Ok("数据库连接".to_string())
}
async fn query(conn: &str, sql: &str) -> Result<Vec<String>, AppError> {
sleep(Duration::from_millis(50)).await;
if sql.is_empty() {
Err(AppError("SQL 不能为空".to_string()))
} else {
Ok(vec![format!("{}: 查询结果1", conn), format!("{}: 查询结果2", conn)])
}
}
async fn close_db(conn: &str) -> Result<(), AppError> {
sleep(Duration::from_millis(20)).await;
println!("关闭 {}", conn);
Ok(())
}
// ? 操作符在 async fn 中正常工作
async fn fetch_records(sql: &str) -> Result<Vec<String>, AppError> {
// 每个 .await 后面都可以用 ?
let conn = connect_db().await?;
let records = query(&conn, sql).await?;
close_db(&conn).await?;
Ok(records)
}
#[tokio::main]
async fn main() {
// 正常路径
match fetch_records("SELECT * FROM users").await {
Ok(records) => {
println!("查询成功:");
for r in &records {
println!(" {}", r);
}
}
Err(e) => println!("错误: {}", e),
}
// 错误路径
match fetch_records("").await {
Ok(_) => println!("不应该到这里"),
Err(e) => println!("预期的错误: {}", e),
}
}await 与循环
use tokio::time::{sleep, Duration, Instant};
async fn process_item(item: &str) -> String {
sleep(Duration::from_millis(50)).await;
format!("[已处理] {}", item)
}
#[tokio::main]
async fn main() {
let items = vec!["数据A", "数据B", "数据C", "数据D", "数据E"];
// === 在 for 循环中 await(顺序执行)===
let start = Instant::now();
println!("=== 循环中顺序 await ===");
let mut results = Vec::new();
for item in &items {
let result = process_item(item).await;
results.push(result);
}
println!("结果: {:?}", results);
println!("耗时: {:?}\n", start.elapsed()); // ~250ms
// === 收集 Future 后并发执行 ===
let start = Instant::now();
println!("=== 并发执行 ===");
let futures: Vec<_> = items.iter()
.map(|item| process_item(item))
.collect();
// futures::future::join_all 并发驱动所有 Future
let results = futures::future::join_all(futures).await;
println!("结果: {:?}", results);
println!("耗时: {:?}\n", start.elapsed()); // ~50ms
// === while 循环中的 await(轮询模式)===
println!("=== 轮询模式 ===");
let start = Instant::now();
let mut count = 0;
while count < 5 {
sleep(Duration::from_millis(100)).await;
count += 1;
println!(" 轮询 #{}: {:?}", count, start.elapsed());
}
}await 与条件分支
use tokio::time::{sleep, Duration};
async fn fast_path() -> String {
sleep(Duration::from_millis(50)).await;
"快速路径完成".to_string()
}
async fn slow_path() -> String {
sleep(Duration::from_millis(200)).await;
"慢速路径完成".to_string()
}
async fn optional_step(should_run: bool) -> Option<String> {
if should_run {
sleep(Duration::from_millis(100)).await;
Some("可选步骤完成".to_string())
} else {
None
}
}
#[tokio::main]
async fn main() {
let use_fast = true;
// if-else 中的 await
let result = if use_fast {
fast_path().await
} else {
slow_path().await
};
println!("条件分支: {}", result);
// match 中的 await
let level = 2;
let msg = match level {
1 => fast_path().await,
2 => slow_path().await,
_ => "未知级别".to_string(),
};
println!("match 分支: {}", msg);
// 可选的 await
if let Some(result) = optional_step(true).await {
println!("可选步骤: {}", result);
}
// let-else 与 await
let Some(result) = optional_step(true).await else {
println!("步骤跳过");
return;
};
println!("let-else: {}", result);
}基本示例
用 .await 构建一个多步骤异步处理流程:
use tokio::time::{sleep, Duration, Instant};
// 模拟数据获取
async fn download(url: &str) -> Result<String, String> {
let delay = if url.contains("fast") { 80 } else { 200 };
sleep(Duration::from_millis(delay)).await;
if url.contains("error") {
Err(format!("下载失败: {}", url))
} else {
Ok(format!("来自 {} 的数据 ({}ms)", url, delay))
}
}
// 模拟数据解析
async fn parse(data: &str) -> Vec<String> {
sleep(Duration::from_millis(50)).await;
data.split_whitespace()
.map(|w| w.to_uppercase())
.collect()
}
// 模拟数据存储
async fn save(items: &[String]) -> usize {
sleep(Duration::from_millis(30)).await;
items.len()
}
#[tokio::main]
async fn main() {
let start = Instant::now();
// 并发下载多个资源
let urls = vec![
"https://fast.example.com/api",
"https://cdn.example.com/data",
"https://fast.example.com/config",
];
println!("=== 并发下载 ===");
let download_futures: Vec<_> = urls.iter()
.map(|url| download(url))
.collect();
let download_results = futures::future::join_all(download_futures).await;
// 处理下载结果
let mut all_items = Vec::new();
for (url, result) in urls.iter().zip(download_results.iter()) {
match result {
Ok(data) => {
println!(" 下载成功: {}", url);
// 顺序解析每个下载的数据
let items = parse(data).await;
println!(" 解析得到 {} 项", items.len());
all_items.extend(items);
}
Err(e) => println!(" {}", e),
}
}
// 保存结果
let saved = save(&all_items).await;
println!("\n保存了 {} 项数据", saved);
println!("总耗时: {:?}", start.elapsed());
// === 超时控制 ===
println!("\n=== 超时控制 ===");
match tokio::time::timeout(
Duration::from_millis(100),
download("https://slow.example.com/huge")
).await {
Ok(Ok(data)) => println!("下载成功: {}", data),
Ok(Err(e)) => println!("下载错误: {}", e),
Err(_) => println!("下载超时!"),
}
// === select! 竞争 ===
println!("\n=== 竞争模式 ===");
tokio::select! {
result = download("https://fast.example.com/a") => {
println!("快速源先完成: {:?}", result);
}
result = download("https://cdn.example.com/b") => {
println!("CDN 源先完成: {:?}", result);
}
}
}常见问题
问题一:.await 会阻塞线程吗?
不会。.await 只是暂停当前异步任务,让出执行权给运行时调度器。线程可以去执行其他就绪的任务。这和 thread::sleep 阻塞整个线程完全不同。
问题二:.await 只能在 async 中使用吗?
是的。.await 只能在 async fn 或 async { } 代码块中使用,在普通函数中使用会编译错误。如果需要在同步代码中等待 Future,需要用运行时的 block_on 方法。
问题三:多个 .await 的执行顺序是什么?
在同一个 async 函数中,多个 .await 是顺序执行的(上一个完成后才执行下一个)。如果需要并发,用 tokio::join!、futures::future::join_all 或 tokio::spawn。
问题四:.await 为什么是后缀语法?
Rust 选择 .await 而不是 await expr 是为了和方法调用链自然衔接。比如 foo().await.bar().await 比 await (await foo()).bar() 更易读。
适用场景
- IO 等待:网络请求、文件读写、数据库查询
- 链式操作:多步依赖的异步操作
- 错误传播:配合
?操作符处理异步结果 - 超时控制:配合
tokio::time::timeout限制等待时间
注意事项
.await只能在async上下文中使用.await不阻塞线程,只暂停当前任务- 顺序
.await是串行的,并发需要join!或spawn .await是后缀语法,放在表达式后面- 异步代码中不要用
std::thread::sleep,会阻塞线程 ?操作符可以和.await配合使用:foo().await?
总结
.await 是等待 Future 完成的关键字,只能在 async 上下文中使用。它不阻塞线程,只暂停当前异步任务,让运行时可以执行其他任务。.await 表达式的值就是 Future 的输出。在同一个 async 函数中,多个 .await 按顺序执行;如果需要并发,用 tokio::join! 或 futures::future::join_all。.await 采用后缀语法,可以自然地嵌入方法链和 ? 操作符(result().await?)。.await 可以在循环、条件分支、match 表达式中使用。配合 tokio::time::timeout 可以给 .await 添加超时限制。