Rust async await (2)

x1957

x1957

Posted on July 16, 2019

Rust async await (2)

Rust async await (1) 里面我们提到了简单的async await目前的语法,想用于实战试试。

我们用异步http请求试试,依赖如下:

[dependencies]
tokio = "0.1.22"
futures-preview = { version = "=0.3.0-alpha.17", features = ["compat"] }
reqwest = "0.9.18"
#![feature(async_await)]

use futures::compat::Future01CompatExt;
use futures::compat::Stream01CompatExt;
use futures::future::{FutureExt, TryFutureExt};
use futures::stream::{StreamExt, TryStreamExt};
use futures::Future;
use reqwest::r#async::{Client, ClientBuilder, Decoder};
use std::io::{self, Write};

async fn download() {
    let client = ClientBuilder::new().build().unwrap();
    let res = client
        .get("https://dev.to/x1957/rust-async-await-2l4c")
        .send()
        .compat()
        .await;
    let mut body = res.unwrap().into_body().compat();
      while let Some(next) = body.next().await {
        let chunk = next.unwrap();
        io::stdout().write_all(&chunk).unwrap();
    }
    println!("\nDone");
}

fn main() {
    let fut = download().unit_error().boxed().compat();
    tokio::run(fut);
}

需要注意几点:
1、use reqwest::r#async::{Client, ClientBuilder, Decoder} 因为reqwest还没有升级,之前的async现在已经是关键字了,所以得用r#
2、.send之后的future是futures01需要compat
3、into_body之后的stream是stream01需要compat

💖 💪 🙅 🚩
x1957
x1957

Posted on July 16, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related