3 ms·
Because then you mess up all the other async tasks that would be spawned by the callee and possibly deadlock your program (without an async runtime in the stdli
by dcow 5y ago
Because then you mess up all the other async tasks that would be spawned by the callee and possibly deadlock your program (without an async runtime in the stdlib).
If you're using `async_std`, right now you simply, explicitly, introduce the runtime:
let fut = async_fn();
let res = async_std::task::block_on(fut)?;
(pulling out the Future into fut is just illustrative, it can of course be a single line) instead of:
let res = async_fn().await?;
So it's already pretty darn easy to do what you want.
Also, here's an easy way to make it feel like a keyword:
use std::result::Result;
use std::error::Error;
use async_std::task::block_on as block;
fn main() -> Result<(), Box<dyn Error>> {
let fut = async_std::fs::read_to_string("./Cargo.toml");
let file = block(fut)?;
println!("{}", file);
Ok(())
}
---
[package]
name = "async-sandbox"
version = "0.1.0"
edition = "2018"
[dependencies]
async-std = "1.10"
One final thing to point out here is that, unlike some other languages, in Rust you can call any async function just like any normal function. The only thing that requires a runtime is resolving the returned future. So it's not so much that functions are colored but that resolving futures needs a runtime and there is none in the current standard lib.
- ibraheemdev 5y agoI think the OP meant that those who did not want async would use block_on, while the async API would just work for those who wanted to use it.
- dcow 5y agoI tried to edit for clarity. The issue is the "bringing in the runtime", or the `async_std` part as you point out elsewhere. I guess I don't see a huge benefit in making a keyword like `block` that aliases `async_std::task::block_on`. Indeed you could just `use async_std::task::block_on as bock;` and be on your way.