Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Await 表达式

Syntax
AwaitExpressionExpression . await

await 表达式是一种语法构造,用于挂起由 std::future::IntoFuture 实现提供的计算,直到给定的 future 准备好产生值。

await 表达式的语法是一个类型实现 IntoFuture trait 的表达式(称为 future 操作数),然后是词法单元 .,然后是 await 关键字。

Await 表达式仅在异步上下文中合法,如 async fn、[async 闭包]或 [async 块]。

更具体地说,await 表达式具有以下效果。

  1. 通过对 future 操作数调用 IntoFuture::into_future 来创建 future。
  2. 将 future 求值为 future tmp
  3. 使用 Pin::new_unchecked 固定 tmp
  4. 然后通过调用 Future::poll 方法并将当前任务上下文传递给它来轮询此固定的 future;
  5. 如果对 poll 的调用返回 Poll::Pending,则 future 返回 Poll::Pending,挂起其状态,以便当周围的异步上下文被重新轮询时,执行返回到步骤 3;
  6. 否则对 poll 的调用必须已返回 Poll::Ready,在这种情况下,Poll::Ready 变体中包含的值用作 await 表达式本身的结果。

2018 Edition differences

Await 表达式仅从 Rust 2018 版本开始可用。

任务上下文

任务上下文指的是当异步上下文本身被轮询时提供给当前异步上下文Context。因为 await 表达式仅在异步上下文中合法,所以必须有某些任务上下文可用。

近似脱糖

实际上,await 表达式大致等同于以下非规范性脱糖:

match operand.into_future() {
    mut pinned => loop {
        let mut pin = unsafe { Pin::new_unchecked(&mut pinned) };
        match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) {
            Poll::Ready(r) => break r,
            Poll::Pending => yield Poll::Pending,
        }
    }
}

其中 yield 伪代码返回 Poll::Pending,当重新调用时,从该点恢复执行。变量 current_context 指的是从异步环境获取的上下文。