繁体   English   中英

如何在 WASI 中使用 Rust 的 async/await 语法

[英]How to use Rust's async/await syntax in WASI

我想用cargo-wasi编译以下代码。

// reqwest = { version = "0.11", features = ["json"] }
// tokio = { version = "1", features = ["full"] }

use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("https://httpbin.org/ip")
        .await?
        .json::<HashMap<String, String>>()
        .await?;
    println!("{:#?}", resp);
    Ok(())
}

尝试编译后出现以下错误,因为mio目前不支持WASI

$ cargo wasi run
   Compiling mio v0.7.9
   Compiling parking_lot v0.11.1
   Compiling serde_json v1.0.64
   Compiling idna v0.2.2
error[E0432]: unresolved import `crate::sys::IoSourceState`
  --> /home/ducaale/.cargo/registry/src/github.com-1ecc6299db9ec823/mio-0.7.9/src/io_source.rs:12:5
   |
12 | use crate::sys::IoSourceState;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys`
... errors omitted

我做了一些研究,到目前为止我发现的例子都没有使用 async/await。 有什么我可以用tokio替换的东西,所以我的代码可以在 WASI 中编译吗?

我尝试运行它,似乎 reqwests crate 无法使用 cargo wasi 或 wasm-pack 正确构建,因为它无法编译 mio(在本地编译时由 tokio 使用)。 在 github 上有人提到 reqwests 可以与 wasm 一起使用,但它还没有完全支持,我找不到太多关于如何使它工作的信息。 听起来目前对于 WASI 上的 HTTP 请求还没有太多解决方案,但是 web-sys 可以用于通过 Node.js 或浏览器发出请求。

看来 tokio 需要特定的功能标志才能与 web 程序集一起使用。 这个问题在底部提到了同步和 rt 标志: https://github.com/tokio-rs/tokio/issues/1597但为了也使用#[tokio:main],你需要“rt-multi -thread”和“宏”功能标志也是如此。

It might also be possible to use wasm bindgen to convert the future into a promise, but that might not work with WASI: https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/

尝试从 tokio 中删除网络:

tokio = { version="1.21.1", features=["rt","sync","time"] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM