Rust wasm-bindgen的 async/await 特性来实现异步编程的示例
本文将介绍一个使用 Rust wasm-bindgen的 async/await 特性来实现异步编程的示例,示例中使用了 wasm-bindgen
将 Rust 代码编译成了 WebAssembly 模块,并在 Node.js 中运行。以下是示例的具体步骤:
-
在
Cargo.toml
中添加必要的依赖,包括js-sys
、spin_sleep
、wasm-bindgen
、wasm-bindgen-futures
、futures-core
和futures-channel-preview
:[package] name = "wasm" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib", "rlib"] [dependencies] js-sys = "0.3.61" spin_sleep = "1.1.1" wasm-bindgen = "0.2.84" wasm-bindgen-futures = "0.4" futures-core = { version = '0.3', default-features = false, optional = true } futures-channel-preview = "0.3.0-alpha.19"
-
在
lib.rs
中添加test()
和test2()
两个异步函数,其中test()
函数启动一个新的异步任务并返回其结果,testAsync()
函数是实际执行的异步任务,而test2()
函数直接返回一个JsValue
:use wasm_bindgen::prelude::*; use spin_sleep::LoopHelper; use wasm_bindgen_futures::spawn_local; use