【问题标题】:How to use Rust's async/await syntax in WASI如何在 WASI 中使用 Rust 的 async/await 语法
【发布时间】:2021-03-10 23:49:48
【问题描述】:

我想用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 doesn't currently support 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

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

【问题讨论】:

    标签: rust wasi


    【解决方案1】:

    我尝试运行它,但似乎 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”和“macros”功能标志。

    也可以使用 wasm bindgen 将 future 转换为 promise,但这可能不适用于 WASI:https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/

    【讨论】:

    • 即使我禁用 tokio 的默认功能并仅启用 syncrt,我似乎也会遇到相同的错误。
    • 我有机会尝试运行代码,但无法使用 reqwests 编译它,但可以在没有 reqwests 的情况下编译,但使用 tokio。我已经更新了答案以解释我的发现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2020-08-19
    • 1970-01-01
    • 2018-05-09
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多