Skip to main content

scope

Function scope 

Source
pub async fn scope<'env, F, T>(f: F) -> T
where F: for<'scope> AsyncFnOnce(&'scope Scope<'scope, 'env>) -> T,
Expand description

Create a scope for spawning tasks that borrow from the enclosing stack frame.

The provided async closure receives a reference to the Scope and returns a future. That future is driven alongside any tasks spawned on the scope; when it completes, any still-running spawned tasks are drained before scope returns its value.

ยงExample

use async_rt::scoped::scope;

let data = vec![1, 2, 3, 4];
let data = &data;
let sum = scope(async |s| {
    let a = s.spawn(async { data[0] + data[1] });
    let b = s.spawn(async { data[2] + data[3] });
    a.await.unwrap() + b.await.unwrap()
})
.await;
assert_eq!(sum, 10);