-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to use async functions on instance methods #1858
Comments
This isn't a problem with wasm-bindgen, it's just how Futures work in general, as you can see here: Because Futures run asynchronously, they always outlive the stack, so they must have the There are generally two workarounds:
|
Thank you very much @Pauan for your detailed answer! I finally understand the problem. I tried applying your workarounds and ran to some problems. The first workaround gives me following error:
The second:
Fortunately, I found a solution after I checked again the wasm-bindgen-futures documentation. Instead of returning the rust future directly, it is converted to a JS promise first. pub fn process(&self, command: String) -> Promise {
let info = JsFuture::from(self.user.info());
let adapter = self.user.adapter();
future_to_promise(async move {
let output = match command.as_str() {
"adapter" => adapter,
"info" => {
match info.await {
Ok(resolved) => {
match resolved.into_serde::<Info>() {
Ok(val) => format!("{:?}", &val),
Err(_) => "Deserialize error".to_string(),
}
},
Err(_) => "Promise error".to_string(),
}
}
_ => String::from("Unknown command")
};
Ok(JsValue::from(output))
})
} Sadly, its a bit more unconvient to write than an async function, but it works as intended. |
I would appreciate if the async book has a chapter on this. I ran into the same issue. |
wasm: added wasm-client cargo feature and enabled corresponding wasm features in cargo deps binding/wasm: updated bindings, notably Author and Subscriber now use Rc<Ref<Api>> objects internally as async methods can only be 'self' and not '&mut self', see rustwasm/wasm-bindgen#1858 for discussion.
Using the async keyword on normal functions works fine, but if I want to use it on a method for an object I get some compiler errors that I assume are lifetime related:
Compiler error:
I tried to implement the fix that the compiler suggests:
But then I get the error that is already mentioned in the issue #1187:
As for now the only workaround working for me is creating a normal async function, that consumes the object and returns it back at the end. The processed data is saved internally by the object.
Usage in JavaScript:
Full workaround-code can be found here: https://github.com/U3W/EasyPass/blob/client-backend/WebService/src/main/rust/src/lib.rs
The text was updated successfully, but these errors were encountered: