小编Kon*_*hel的帖子

如何在 Node.js 环境中从 WebAssembly (Rust) 调用异步 JavaScript 导入函数?

让我们考虑一个示例导入对象,如下所示:

const importObject = {
  exampleAsyncImportFunction: async () => fs.readFile("./someExampleFile.txt", "utf-8") // returns Promise<String>
};
Run Code Online (Sandbox Code Playgroud)

我想在我的 Rust 编写的 WASM 模块中使用它,类似于:

#[wasm_bindgen]
extern "C" {
  pub async fn exampleAsyncImportFunction() -> JsValue; // Importing the JS-Function
}

#[wasm_bindgen]
pub async fn exampleExportFunction() -> Result<JsValue, JsValue> {
  let theJSPromise = exampleAsyncImportFunction(); // Call the async import function
  let promiseResult = theJSPromise.await; // Execute the async import function
  // Do sth with the result
  OK(JsValue::UNDEFINED)
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会导致无法访问的错误。有趣的是,当 JavaScript 函数返回一个字符串时,它确实有效,如下所示:

const importObject = {
  exampleAsyncImportFunction: …
Run Code Online (Sandbox Code Playgroud)

node.js rust async-await webassembly wasm-bindgen

5
推荐指数
1
解决办法
1898
查看次数

标签 统计

async-await ×1

node.js ×1

rust ×1

wasm-bindgen ×1

webassembly ×1