异步函数
TIP
为了使用 async fn ,你必须开启 napi 的 async 或 tokio_rt 特性:
Cargo.toml
toml
[dependencies]
napi = { version = "3", features = ["async", "tokio_fs"] }
napi-derive = "3"
下面的例子使用 tokio_fs 子特性。只启用 addon 实际使用的 Tokio API。
你可以通过 AsyncTask 和 ThreadsafeFunction 做很多 异步/多线程 的工作,但有时你可能想直接使用 Rust 异步生态系统中的包。
启用 async 或 tokio_rt 后,NAPI-RS 会提供 Tokio 运行时。如果你在导出的
async fn 中 await 一个 Tokio future,NAPI-RS 会在该运行时中执行它,
并把结果转换为 JavaScript Promise。
lib.rs
rust
use napi::bindgen_prelude::*;
use napi::tokio::fs;
use napi_derive::napi;
#[napi]
pub async fn read_file_async(path: String) -> Result<Buffer> {
let content = fs::read(path).await?;
Ok(content.into())
}
⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
index.d.ts
ts
export function readFileAsync(path: string): Promise<Buffer>