如何等待第一个k期货?

F.C*_*hen 6 rust async-await

假设我们有 n 个服务器,我们只需要 k < n 个响应。

我知道 futures::join_all 可用于等待所有 n 个期货,但我希望我的程序在 k 个响应后完成等待。

是否有类似于 join_all 的东西可以用来等待前 k 个响应?

Frx*_*rem 5

您可以为此使用(异步迭代器)。您可以将其FuturesUnordered用作一个无序的期货集合,它可以用作一个流,您可以在其中按照它们完成的顺序获取每个期货的结果。然后,您可以将其与.take(n)仅获取n流的第一项相结合,然后.collect::<Vec<_>>()等待流完成并将结果收集到 a 中Vec

use futures::prelude::*;
use futures::stream::FuturesUnordered;

let futures = vec![
    // assume `f(n, t)` = sleep for `t` millis, then return `n`
    f(1, 1000),
    f(2, 10),
    f(3, 105),
    f(4, 40),
    f(5, 70),
    f(6, 270),
];

// create unordered collection of futures
let futures = futures.into_iter().collect::<FuturesUnordered<_>>();

// use collection as a stream, await only first 4 futures to complete
let first_4 = futures.take(4).collect::<Vec<_>>().await;

// note: any remaining futures will be cancelled automatically when the
// stream is consumed

// check with expected result, based on the order of completion
assert_eq!(first_4, vec![2, 4, 5, 3]);
Run Code Online (Sandbox Code Playgroud)

游乐场示例


编辑:如果你还想获得完成未来的索引,你可以使用这个:

// create unordered collection of futures with indices
let futures = futures
        .into_iter()
        .enumerate()
        .map(|(i, fut)| fut.map(move |res| (i, res)))
        .collect::<FuturesUnordered<_>>()
Run Code Online (Sandbox Code Playgroud)

游乐场示例