DEV Community

x1957
x1957

Posted on

Rust async await (1)

Rust version:

rustc 1.38.0-nightly (69656fa4c 2019-07-13)

打开async/await的future:

#![feature(async_await)]
#![feature(async_await)]

async fn get()->i32 {
    println!("start");
    std::thread::sleep(std::time::Duration::from_millis(1000));
    1
}

async fn p() {
    let n = get().await;
    println!("n = {}", n);
}

fn main() {
    let fut = p();
    println!("called p");
    futures::executor::block_on(fut);
}

定义了一个简单的get函数,返回1

p里面调用get并打印1

async和JavaScript的类似,返回的是future(js的是promise),所以在Rust里面我们还需要一个executor来Run这个future,这里我们future用的版本是:

futures-preview = { version = "=0.3.0-alpha.17", features = ["compat"] }

主要原因就是async返回的是std::future::Future,而我们大部分三方库还是用的futures这个库,比如tokio,我们用tokio::run来试试会有个报错

  --> src/main.rs:21:5
   |
21 |     tokio::run(fut);
   |     ^^^^^^^^^^ the trait `futures::future::Future` is not implemented for `impl std::future::Future`
   |
   = note: required by `tokio::runtime::threadpool::run`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `async-await`.

To learn more, run the command again with --verbose.

tokio::run 是给 futures::future::Future,但是我们 async 的是 std::future::Future

现在最大的问题就是三方库还没有支持std future,所以如果要用就得compat一下

#![feature(async_await)]

use futures::compat::Future01CompatExt;
use futures::future::{FutureExt, TryFutureExt};

async fn get()->i32 {
    println!("start");
    std::thread::sleep(std::time::Duration::from_millis(1000));
    1
}

async fn p() {
    let n = get().await;
    println!("n = {}", n);
}

fn main() {
    let fut = p().unit_error().boxed().compat();
    println!("called p");
    tokio::run(fut);
}

Top comments (0)