我有以下回调,我注册到onsubmit
事件。
use gloo::net::http::Request;
use yew::prelude::*;
let on_submit = Callback::from(async move |ev: FocusEvent| {
ev.prevent_default();
let res = Request::post("https://formsubmit.co/srineshnisala@gmail.com")
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
});
然而,当我使用async
--> src/pages/contact/contact.rs:26:36
|
26 | let on_submit = Callback::from(async move |ev: FocusEvent| {
| _____________________--------------_^
| | |
| | required by a bound introduced by this call
27 | | ev.prevent_default();
28 | |
29 | | let res = Request::post("https://formsubmit.co/srineshnisala@gmail.com")
... |
34 | | assert_eq!(res.status(), 200);
35 | | });
| |_____^ expected `()`, found opaque type
|
::: /home/s1n7ax/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/future/mod.rs:72:43
|
72 | pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
| ------------------------------- the found opaque type
|
= note: expected unit type `()`
found opaque type `impl Future<Output = ()>`
= note: required for `yew::Callback<yew::FocusEvent>` to implement `From<[closure@src/pages/contact/contact.rs:26:36: 26:63]>`
锈版本:
rustc 1.66.0-nightly (01af5040f 2022-10-04)
包版本:
yew = "0.19.3"
yew-router = "0.16.0"
gloo = "0.7.0" # console log and stuff
hyper = "0.14.19" # http requests
如何使用异步函数作为回调?
您不能从异步闭包中创建Callback
,但您可以使用wasm_bindgen_futures::spawn_local
在当前线程上运行Future
:
use gloo::net::http::Request;
use yew::prelude::*;
let on_submit = Callback::from(move |ev: FocusEvent| {
ev.prevent_default();
wasm_bindgen_futures::spawn_local(async move {
let res = Request::post("https://formsubmit.co/srineshnisala@gmail.com")
.send()
.await
.unwrap();
assert_eq!(res.status(), 200);
});
});
你不能。Callback::from(impl Fn(In) -> Out)
是构造非noopCallback
的唯一方法。
你必须要么使用block_on
同步执行异步操作,要么使用回调仅在外部异步上下文中注册操作,例如使用通道。