让我们考虑一个如下所示的导入对象示例:
const importObject = {
exampleAsyncImportFunction: async () => fs.readFile("./someExampleFile.txt", "utf-8") // returns Promise<String>
};
我想在用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)
}
不幸的是,这会导致一个无法访问的错误。有趣的是,当JavaScript函数返回一个字符串时,它确实可以工作,就像这样:
const importObject = {
exampleAsyncImportFunction: async () => "Some dummy content" // returns Promise<String> as well
};
当然,一个异步导入函数应该执行一些实际的异步任务,否则最好使用同步函数。
我尝试进行了一些研究,并找到了 'js_sys::Promise'(在 Rust 中表示 JS-Promise)和 'wasm_bindgen_futures::JsFuture'(可以将 JS-Promise 转换为 Rust-Future)。但是我不明白这些类型如何帮助解决问题,以及它们在此上下文中应该如何使用。
此外,JS-Import-Function 的返回类型声明为 'JsValue',似乎也实现了 'Future' 特性。我理解由于此,可以 'await' 等待结果。但是我很困惑,实际的底层类型是什么(JsFuture、Promise 还是其他什么...)。
我希望有人可以帮助我解决这个问题,并在解释所有类型之间的关系方面进行一些说明(特别是关于 JsValue 的部分)。
预先感谢您!
importObject
连接到extern "C"
函数吗?我猜你使用了wasm-pack
,然后通过require
模块来实现的? - frankenappsmodule.exports = { // The import functions like above }
。在 rust 中,我像上面描述的那样导入 JS 函数。唯一的区别是,'extern "c"' 块被注释为 **#[wasm_bindgen(module = "/imports.js")]**,以引用 JS 文件。从主机端,我只需使用await import("./path")
导入包含 WASM 模块的生成文件夹即可。 - Konrad Koschel