A Rust Async Primer-Pt 3

Photo by Markus Spiske on Unsplash
[package]
name = "rust-async"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
async-std = "1.12.0"
futures = "0.3"
rand = "0.8.5"
use std::time::{Instant, Duration};
use async_std::task;
use rand::Rng;
fn main() {
let start_time = Instant::now();
task::block_on(async_main());
print!("Completed in {} ms", start_time.elapsed().as_millis());
}async fn async_main() {
let long_running_stuff = make_coffee_and_bacon();
let other_stuff = make_eggs();
futures::join!(long_running_stuff, other_stuff);
}
async fn make_coffee_and_bacon() {
futures::join!(make_coffee(), make_bacon());
}
async fn make_coffee() {
burning_time("Coffee".to_string()).await;
}
async fn make_eggs() {
burning_time("Eggs".to_string()).await;
}
async fn make_bacon() {
burning_time("Bacon".to_string()).await;
}
async fn burning_time(breakfast_item: String) {
let mut rng = rand::thread_rng();
println!("{} started!", breakfast_item);
let sleep_duration = Duration::from_millis(rng.gen_range(100..1500));
task::sleep(sleep_duration).await; println!("{} finished after {:?} ms", breakfast_item, sleep_duration.as_millis());
}
└─[0] <git:(master b7644d4✱) > cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.03s
Running `target/debug/rust-async`
Coffee started!
Bacon started!
Eggs started!
Bacon finished after 211 ms
Eggs finished after 430 ms
Coffee finished after 1318 ms
Completed in 1319 ms%
┌─[clayratliff@pop-os] - [~/PersonalGithub/rust-async] - [2022-07-01 05:59:36]
└─[0] <git:(master b7644d4✱) > cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.03s
Running `target/debug/rust-async`
Coffee started!
Bacon started!
Eggs started!
Coffee finished after 255 ms
Eggs finished after 1429 ms
Bacon finished after 1499 ms
Completed in 1500 ms%
[package]
name = "rust-async"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
async-std = "1.12.0"
futures = "0.3"
serde = "1.0.138"
surf = "2.3.2"
{
"Global Quote": {
"01. symbol": "IBM",
"02. open": "141.0000",
"03. high": "141.6700",
"04. low": "139.2600",
"05. price": "141.1200",
"06. volume": "4012106",
"07. latest trading day": "2022-07-01",
"08. previous close": "141.1900",
"09. change": "-0.0700",
"10. change percent": "-0.0496%"
}
}
use async_std::task;
use futures::join;
use serde::Deserialize;
use std::time::Instant;
use surf::Result;
#[derive(Deserialize)]
struct GlobalQuote {
#[serde(rename = "01. symbol")]
symbol: String,
#[serde(rename = "02. open")]
open: String,
#[serde(rename = "03. high")]
high: String,
#[serde(rename = "04. low")]
low: String,
#[serde(rename = "05. price")]
price: String,
}
#[derive(Deserialize)]
struct TickerData {
#[serde(rename = "Global Quote")]
full_ticker: GlobalQuote,
}
fn main() {
let start_time = Instant::now();
task::block_on(async_main());
println!("Completed in {} ms", start_time.elapsed().as_millis());
}
async fn async_main() {
let api_key = "API_KEY";
let ibm_symbol = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM&apikey={}",
api_key
);
let tesla_symbol = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=TSLA&apikey={}",
api_key
);
let apple_symbol = format!(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=AAPL&apikey={}",
api_key
);

let first_symbol = get_ticker(ibm_symbol);
let second_symbol = get_ticker(tesla_symbol);
let third_symbol = get_ticker(apple_symbol);
let (result1, result2, result3) = join!(first_symbol, second_symbol, third_symbol);

println!("IBM ticker price: {}", result1.unwrap().price);
println!("Tesla ticker price: {}", result2.unwrap().price);
println!("Apple ticker price: {}", result3.unwrap().price);
}
async fn get_ticker(url: String) -> Result<GlobalQuote> {
let start_time = Instant::now();
let TickerData { full_ticker } = surf::get(&url).recv_json().await?;
println!("Async completed in {} ms", start_time.elapsed().as_millis());
Ok(full_ticker)
}
Async completed in 226 ms
Async completed in 232 ms
Async completed in 278 ms
IBM ticker price: 141.1200
Tesla ticker price: 681.7900
Apple ticker price: 138.9300
Completed in 281 ms

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Clay Ratliff

Clay Ratliff

27 Followers

I am a jack of all trades and a master of none. An all-around neophile, currently disguised as a Solution Architect.