1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use futures::Future;
use std::{
cell::RefCell,
ops::Deref,
rc::Rc,
};
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::{
future_to_promise,
JsFuture,
};
pub struct UnwrappedPromise<S, E> {
promise_state: Rc<RefCell<PromiseState<S, E>>>,
#[allow(dead_code)]
future: Box<dyn Future<Item = JsValue, Error = JsValue>>,
}
impl<S: 'static, E: 'static> UnwrappedPromise<S, E> {
pub fn new(
future: impl Future<Item = S, Error = E> + 'static,
callback: Option<impl Fn() + 'static>,
) -> Self {
let data = Rc::new(RefCell::new(PromiseState::Pending));
let data_1 = data.clone();
let data_2 = data.clone();
let callback = Rc::new(RefCell::new(callback));
let callback_1 = callback.clone();
let future = future
.map(move |s| {
*data_1.borrow_mut() = PromiseState::Success(s);
if let Some(ref cb) = *callback.borrow() {
cb();
};
JsValue::NULL
})
.map_err(move |e| {
*data_2.borrow_mut() = PromiseState::Error(e);
if let Some(ref cb) = *callback_1.borrow() {
cb();
};
JsValue::NULL
});
let future = Box::new(JsFuture::from(future_to_promise(future)));
let unwrapped_promise = UnwrappedPromise {
promise_state: data,
future,
};
unwrapped_promise
}
}
impl<S, E> Deref for UnwrappedPromise<S, E> {
type Target = Rc<RefCell<PromiseState<S, E>>>;
fn deref(&self) -> &Rc<RefCell<PromiseState<S, E>>> {
&self.promise_state
}
}
pub enum PromiseState<S, E> {
Pending,
Success(S),
Error(E),
}