Rust 等待一份锈迹斑斑的期货清单

Rust 等待一份锈迹斑斑的期货清单,rust,future,Rust,Future,我试图创造一个未来,不断地发现新的工作要做,然后为这些工作项目维护一套未来。我想确保我的主要未来不会因为工作长期受阻而同时完成我的工作 这里是我试图做的一个粗略的概述。具体地说,isDone并不存在,而且据我从文档中了解,这不一定是在Rust中使用期货的有效方式。我做这种事情的方式是什么 use std::collections::HashMap; use tokio::runtime::Runtime; async fn find_work() -> HashMap<i64, S

我试图创造一个未来,不断地发现新的工作要做,然后为这些工作项目维护一套未来。我想确保我的主要未来不会因为工作长期受阻而同时完成我的工作

这里是我试图做的一个粗略的概述。具体地说,
isDone
并不存在,而且据我从文档中了解,这不一定是在Rust中使用期货的有效方式。我做这种事情的方式是什么

use std::collections::HashMap;
use tokio::runtime::Runtime;

async fn find_work() -> HashMap<i64, String> {
    // Go read from the DB or something...
    let mut work = HashMap::new();
    work.insert(1, "test".to_string());
    work.insert(2, "test".to_string());
    return work;
}

async fn do_work(id: i64, value: String) -> () {
    // Result<(), Error> {
    println!("{}: {}", id, value);
}

async fn async_main() -> () {
    let mut pending_work = HashMap::new();
    loop {
        for (id, value) in find_work().await {
            if !pending_work.contains_key(&id) {
                let fut = do_work(id, value);
                pending_work.insert(id, fut);
            }
        }

        pending_work.retain(|id, fut| {
            if isDone(fut) {
                // do something with the result
                false
            } else {
                true
            }
        });
    }
}

fn main() {
    let runtime = Runtime::new().unwrap();
    let exec = runtime.executor();

    exec.spawn(async_main());
    runtime.shutdown_on_idle();
}
使用std::collections::HashMap;
使用tokio::runtime::runtime;
异步fn find_work()->HashMap{
//去读数据库什么的。。。
让mut工作=HashMap::new();
插入(1,“test.”to_string());
插入(2,“test.”to_string());
返回工作;
}
异步fn do_work(id:i64,值:String)->(){
//结果{
println!(“{}:{}”,id,value);
}
async fn async_main()->(){
让mut pending_工作=HashMap::new();
环路{
查找工作()中的(id,值)。等待{
if!挂起的\u工作。包含\u键(&id){
让fut=do_工作(id,值);
待定工作。插入(id,fut);
}
}
待定工作。保留(| id,未来){
如果是isDone(fut){
//对结果做点什么
假的
}否则{
真的
}
});
}
}
fn main(){
让runtime=runtime::new().unwrap();
让exec=runtime.executor();
exec.spawn(async_main());
runtime.shutdown_on_idle();
}

也许你在寻找类似的东西,或者感谢你的建议,我看了这些,但不幸的是
加入!
阻止了我需要检查新工作的主循环,并且
选择
加入
接受固定数量的未来,而不是地图或vec,因此它们最好使用起来有点笨拙。我会的尝试
select
out,看看它是否工作正常。期货只有在被轮询时才起作用,所以也许你应该
poll()
他们?如果未来完成了,你会得到
poll::Ready
,否则-
poll::Pending
,这与你的
isDone()相同
方法接收到它返回一个带有两个变量的枚举,而不是true/false。这与描述的不完全一样,但我最终使用了
futures::future::join_all
(),它可以接受任何INTERACTOR,对我来说已经足够好了。@Nick post这是一个答案