Asynchronous Data Fetcher
This challenge focuses on implementing an asynchronous function in Rust to fetch data from a simulated external source. Asynchronous programming is crucial for building responsive and efficient applications, especially when dealing with I/O-bound operations like network requests. Your task is to create a function that simulates fetching data and returns it asynchronously.
Problem Description
You are tasked with creating an asynchronous function fetch_data that simulates fetching data from an external source. This function should take a task_id (an integer) as input, simulate a delay (using tokio::time::sleep), and then return a Result<String, String>. The Result should contain a success message if the task completes successfully, or an error message if it fails.
The simulation should work as follows:
- If
task_idis even, the function should simulate a successful fetch after a delay of 500 milliseconds. The success message should be "Data fetched successfully for task ID: {task_id}". - If
task_idis odd, the function should simulate a failed fetch after a delay of 250 milliseconds. The error message should be "Failed to fetch data for task ID: {task_id}".
The function must be asynchronous using the async keyword and utilize tokio::time::sleep for the simulated delays. The function should return a Result<String, String> to indicate success or failure.
Examples
Example 1:
Input: task_id = 2
Output: Ok("Data fetched successfully for task ID: 2")
Explanation: The task ID is even, so the function sleeps for 500ms and returns a success message.
Example 2:
Input: task_id = 1
Output: Err("Failed to fetch data for task ID: 1")
Explanation: The task ID is odd, so the function sleeps for 250ms and returns an error message.
Example 3:
Input: task_id = 0
Output: Ok("Data fetched successfully for task ID: 0")
Explanation: The task ID is even, so the function sleeps for 500ms and returns a success message.
Constraints
- The
task_idwill be a non-negative integer (0 or greater). - The function must use
tokio::time::sleepto simulate delays. - The function must be asynchronous (
async fn). - The function must return a
Result<String, String>. - The delays are approximate and do not need to be perfectly precise.
- You must use the
tokiocrate for asynchronous operations.
Notes
- Remember to add
#[tokio::main]to your main function to run the asynchronous code. - Consider using
tokio::time::Durationto specify the sleep durations. - The
Resulttype is crucial for handling potential errors in asynchronous operations. - This problem is designed to test your understanding of
asyncfunctions,tokio::time::sleep, andResulttypes in Rust. Focus on correctly implementing the asynchronous behavior and error handling.