rust - 如何等待第一个k future ?

标签 rust async-await

假设我们有 n 个服务器,我们只需要 k < n 个响应。
我知道 futures::join_all 可用于等待所有 n 个 future ,但我希望我的程序在 k 个响应后完成等待。
是否有类似于 join_all 的东西可以用来等待前 k 个响应?

最佳答案

您可以使用 streams (异步迭代器)为此。您可以使用 FuturesUnordered 作为一个无序的 future 集合,它可以用作一个流,您可以在其中按照它们完成的顺序获得每个 future 的结果。然后你可以把它和 .take(n) 结合起来只取第一个 n流的项目,然后 .collect::<Vec<_>>() 等待流结束并在 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]);
Playground example

编辑:如果你还想获得完成 future 的索引,你可以使用这个:
// create unordered collection of futures with indices
let futures = futures
        .into_iter()
        .enumerate()
        .map(|(i, fut)| fut.map(move |res| (i, res)))
        .collect::<FuturesUnordered<_>>()
Playground example

关于rust - 如何等待第一个k future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68448854/

相关文章:

function - 如何在 Rust 中使用多参数字符串函数?

c# - 为并行 API 调用添加延迟

javascript - 如何从 puppeteer 异步函数内部返回值(对象)?

vue.js - Vuex 中的异步/等待操作

c# - 等待多个独立任务的最佳方法/实践是什么?

rust - 在 Rust 1.26 中推断存在类型(impl Trait)的生命周期

plugins - 如何从过程宏中处理扩展宏?

async-await - 在 Flutter 中使用 Future 在异步任务中使用进度条对话框

rust - 如何指定特征迭代器?

rust - 当谓词返回 Result<bool, _> 时如何过滤迭代器?