我有以下方法:
pub async fn get_projects(organizations: &Vec<Organization>) -> Vec<Project> {
// Define collection to hold the projects.
let mut result = Vec::new();
// Create a collection of tasks to retrieve the projects.
let mut tasks = Vec::new();
// Create a new task for each organization.
for organization in organizations.iter() {
if !organization.is_pat_valid {
// If the PAT for the organization is not valid, do not try to retrieve the projects for it.
continue;
}
// Create a new task to retrieve the projects for the organization and store it.
tasks.push(repositories::devops::get_projects(
&organization.pat,
&organization.name,
))
}
// Wait for all tasks to finish.
let task_results = join_all(tasks).await;
// Add the projects from the resolved tasks all to the result collection.
for task_result in task_results.iter() {
match task_result {
Ok(projects) => result.extend(projects),
Err(error) => println!("Error: {}", error),
}
}
return result;
}
我想在这里做的是并行执行异步代码,最后等待所有任务,然后将所有任务结果一起添加到一个集合中,我返回。
在代码部分:
for task_result in task_results.iter() {
match task_result {
Ok(projects) => result.extend(projects),
Err(error) => println!("Error: {}", error),
}
}
我想添加到我的结果中的
projects
来自&Project类型,而不是Project。如果我将 result
vec 更改为 Vec<&Project>
我收到以下错误:
return result;
| ^^^^^^ returns a value referencing data owned by the current function
我对 RUST 完全陌生,我不知道如何返回这个结果,因为似乎所有任务的结果都在我的 fn 范围内。
旧的、性能不佳的解决方案是这样实现的:
pub async fn get_projects(organizations: Vec<Organization>) -> Vec<Project> {
let mut result: Vec<Project> = vec![];
for organization in organizations.iter() {
if (!organization.is_pat_valid) {
continue;
}
let organization_projects =
repositories::devops::get_projects(&organization.pat, &organization.name).await;
match organization_projects {
Ok(projects) => {
result.extend(projects);
}
Err(error) => {
println!("Error: {}", error);
}
}
}
return result;
}
这应该更慢,因为 asyn fn 不是并行执行的,但至少它起作用了。