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

标签 rust 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 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 中编译?

最佳答案

我尝试运行它,但似乎 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/

关于rust - 如何在 WASI 中使用 Rust 的 async/await 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574538/

相关文章:

特征作为函数的返回值

datetime - BadFormat 在使用 Chrono 时将字符串解析为最新

rust - 了解Rust和类型系统

rust - 返回本地String作为切片(&str)

clang - Emscripten 和 Clang 在 WebAssembly 编译方面有什么区别

c++ - 如何减小 WASM 二进制文件的大小?

node.js - 在 Node.js 中导入正确的 Wasi 模块

rust - 使用 serde 时如何将向量 'flatten' 生成多个 XML 元素?