我正在遵循使用 web-sys 设置 WebRTC 数据通道的指南。我可以复制和粘贴代码,它可以正确编译。start() 函数是异步的,这使得在主范围内等待JsFuture成为可能,但是我试图将这个等待移动到onmessage_callback
块中。只需将这一行添加到原始实现中,我就有了:
let onmessage_callback =
Closure::wrap(
Box::new(move |ev: MessageEvent| {
let desc = JsFuture::from(pc1.create_offer()).await.unwrap();
match ev.data().as_string() {
Some(message) => {
console_warn!("{:?}", message);
dc1_clone.send_with_str("Pong from pc1.dc!").unwrap();
}
None => {}
}
}) as Box<dyn FnMut(MessageEvent)>,
);
dc1.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
onmessage_callback.forget();
一旦我编译了这个,我当然会得到一个错误,说等待未来desc
只能在异步上下文中。我想我可以在定义函数async
时添加关键字:FnMut
let onmessage_callback =
Closure::wrap(
Box::new(move |ev: MessageEvent| async { // <-- async
let desc = JsFuture::from(pc1.create_offer()).await.unwrap();
match ev.data().as_string() {
Some(message) => {
console_warn!("{:?}", message);
dc1_clone.send_with_str("Pong from pc1.dc!").unwrap();
}
None => {}
}
}) as Box<dyn FnMut(MessageEvent)>,
);
dc1.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
onmessage_callback.forget();
但是当我编译这个时,我得到以下错误:
error[E0271]: type mismatch resolving `<[closure@src/lib.rs:48:22: 57:14] as FnOnce<(MessageEvent,)>>::Output == ()`
--> src/lib.rs:48:13
|
48 | / Box::new(move |ev: MessageEvent| async {
49 | | let desc = JsFuture::from(pc1.create_offer()).await.unwrap();
50 | | match ev.data().as_string() {
51 | | Some(message) => {
... |
56 | | }
57 | | }) as Box<dyn FnMut(MessageEvent)>,
| |______________^ expected `()`, found opaque type
|
= note: expected unit type `()`
found opaque type `impl Future<Output = [async output]>`
= note: required for the cast to the object type `dyn FnMut(MessageEvent)`
我不知道如何继续这个,我认为错误是说回调返回一个未来,但它应该是无效的。
如何定义异步回调?