Understanding async and await
The async
and await
syntax manages the same concepts covered in the previous section, however, there are some nuances. Instead of simply spawning off threads, we create futures and then manipulate them as and when needed.
In computer science, a future is an unprocessed computation. This is where the result is not yet available, but when we call or wait, the future will be populated with the result of the computation. Futures can also be referred to as promises, delays, or deferred. In order to explore futures, we will create a new Cargo project, and utilize the futures created in the Cargo.toml
file:
[dependencies] futures = "0.3.5"
Now we have our futures, we can define our own async
function in the main.rs
file:
async fn do_something(number: i8) -> i8 { println!("number {} is running", number); let two_seconds = time::Duration::new(2, 0); thread...