How to start this function simultaneously
I tried using thread in which I get borrowed data escapes outside of function
for item in 0..10{
download_image(
chapter_hash, // &str
image, // &str
name, // &str
title, // &str
vol, // &str
chapter, // &str
item, // usize
).await;
};
What I would like to do is run this function at same time.
EDIT
I added some comments, hope u can make head and tails from code.
It simply searches json for data and download file from these data
async fn download_chapter(
json: String,
name: &str,
title: &str,
vol: &str,
chapter: &str,
folder_name: &str,
) {
match serde_json::from_str(&json) {
Ok(json_value) => match json_value {
Value::Object(obj) => {
if let Some(data_array) = obj.get("chapter") {
// checks if chapter is in the json and store it in value
if let Some(chapter_hash) = data_array.get("hash").and_then(Value::as_str) {
// checks if hash is in chapter and store it in value
if let Some(images1) = data_array.get("data").and_then(Value::as_array) {
// same but with data
let images_length = images1.len(); // .and_then(Value::as_array) if just for length
if let Some(images) = data_array.get("data") {
// this json is [{...}, {...}]
let folder_path =
format!("{} - {}Ch.{} - {}", name, vol, chapter, title);
// Code for creating folder
let pb = ProgressBar::new(images_length as u64);
pb.set_style(
ProgressStyle::default_bar()
.template(" [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({percent}%) {msg}")
.progress_chars("#>-"),
);
for item in 0..images_length {
if let Some(image) = images.get(item) {
// Formatting file path
let file_name = format!(
"{} - {}Ch.{} - {} - {}.jpg",
name,
vol,
chapter,
title,
&item + 1
);
let file_path = format!(
"{}",
file_name
.replace('<', "")
.replace('>', "")
.replace(':', "")
.replace('|', "")
.replace('?', "")
.replace('*', "")
.replace('/', "")
.replace('\\', "")
.replace('"', "")
.replace('\'', "")
);
// The function that can run in threads
download_image(
chapter_hash,
image,
name,
title,
vol,
chapter,
item,
)
.await;
pb.inc(1);
} else {
println!("Image not found")
}
}
pb.finish_with_message("Done downloading");
} else {
println!("Missing data for chapter")
}
} else {
println!("Missing data for chapter")
}
} else {
println!("Chapter number missing")
}
} else {
println!(" JSON does not contain a 'chapter' array.");
}
}
_ => {
println!(" JSON is not an object.");
}
},
Err(err) => println!(" Error parsing JSON: {}", err),
}
}
As you guys suggested I change it, and it works just as expected
It runs max 12 threads at the time, probably because I have 12 thread processor
let tasks = (0..images_length).map(|item| {
if let Some(image_tmp) = images.get(item) {
let image_temp = image_tmp.to_string();
// code for creating directory
let chapter_hash = chapter_hash.to_string();
let image = image_temp.trim_matches('"').to_string();
let name = name.to_string();
let title = title.to_string();
let vol = vol.to_string();
let chapter = chapter.to_string();
tokio::spawn(async move {
download_image(
&chapter_hash,
&image,
&name,
&title,
&vol,
&chapter,
item,
)
.await;
})
} else {
tokio::spawn(async move {
download_image("", "", "", "", "", "", 0).await;
})
}
});
let _: Vec<_> =
futures::future::join_all(tasks).await.into_iter().collect();