-
Notifications
You must be signed in to change notification settings - Fork 177
/
promise_future.rs
211 lines (198 loc) · 8.02 KB
/
promise_future.rs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use std;
use std::pin::Pin;
use webcore::value::{Value, ConversionError};
use webcore::try_from::{TryInto, TryFrom};
use webcore::executor;
use webapi::error;
use futures_core::{Future, TryFuture, Poll};
use futures_core::task::LocalWaker;
use futures_util::{FutureExt, TryFutureExt};
use futures_channel::oneshot::Receiver;
use webcore::discard::DiscardOnDrop;
use webcore::serialization::JsSerialize;
use super::promise::{Promise, DoneHandle};
/// Asynchronously runs the [`Future`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.Future.html)
/// on the current thread and then immediately returns. This does *not* block the current thread.
///
/// This function should normally be called only once in `main`, it is usually not needed to call it multiple times. If you want to run
/// multiple Futures in parallel you should use [`join`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/macro.join.html)
/// or [`try_join`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/macro.try_join.html).
///
/// ----
///
/// There are two types of Futures:
///
/// 1. By default Futures do not have any sort of error handling, and so they can be spawned directly:
///
/// ```rust
/// use stdweb::spawn_local;
///
/// fn main() {
/// spawn_local(
/// create_some_future()
/// );
/// }
/// ```
///
/// If you want to retrieve the return value of the Future, you can use the various asynchronous
/// [`FutureExt`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.FutureExt.html)
/// methods, such as [`map`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.FutureExt.html#method.map) or
/// [`inspect`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.FutureExt.html#method.inspect):
///
/// ```rust
/// use stdweb::spawn_local;
/// use futures::future::FutureExt;
///
/// fn main() {
/// spawn_local(
/// create_some_future()
/// .map(|x| {
/// println!("Future finished with value: {:#?}", x);
/// })
/// );
/// }
/// ```
///
/// 2. However, some Futures return `Result`, and in that case you will need to deal with the `Result` somehow.
///
/// This is very common, because JavaScript Promises always return `Result` (because they might error).
///
/// In that case you can use the various asynchronous
/// [`TryFutureExt`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html)
/// methods, such as [`map_ok`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html#method.map_ok),
/// [`map_err`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html#method.map_err), or
/// [`unwrap_or_else`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html#method.unwrap_or_else):
///
/// ```rust
/// use stdweb::spawn_local;
/// use futures::future::TryFutureExt;
///
/// fn main() {
/// spawn_local(
/// create_some_future()
/// .map_ok(|x| {
/// println!("Future finished with value: {:#?}", x);
/// })
/// .unwrap_or_else(|e| handle_error_somehow(e))
/// );
/// }
/// ```
///
/// It is very common to want to print the errors to the console, and so as a convenience you can use the [`unwrap_future`](fn.unwrap_future.html) function:
///
/// ```rust
/// use stdweb::{spawn_local, unwrap_future};
/// use futures::future::TryFutureExt;
///
/// fn main() {
/// spawn_local(
/// unwrap_future(create_some_future()
/// .map_ok(|x| {
/// println!("Future finished with value: {:#?}", x);
/// }))
/// );
/// }
/// ```
///
/// If you don't need the return value from the Future, then it is even easier, since you don't need
/// [`map_ok`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html#method.map_ok):
///
/// ```rust
/// use stdweb::{spawn_local, unwrap_future};
///
/// fn main() {
/// spawn_local(
/// unwrap_future(create_some_future())
/// );
/// }
/// ```
#[inline]
pub fn spawn_local< F >( future: F ) where F: Future< Output = () > + 'static {
// TODO does this need to use PinBox instead ?
let future: executor::BoxedFuture = Box::new( future ).into();
executor::spawn_local( future );
}
/// Prints an error to the console and then panics.
///
/// If you're using Futures, it's more convenient to use [`unwrap_future`](fn.unwrap_future.html) instead.
///
/// # Panics
/// This function *always* panics.
#[inline]
pub fn print_error_panic< A: JsSerialize >( value: A ) -> ! {
js! { @(no_return)
console.error( @{value} );
}
panic!();
}
/// Takes in an input
/// [`Future`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.Future.html)
/// (which returns `Result<A, B>`) and returns a new
/// [`Future`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.Future.html)
/// (which returns `A`).
///
/// If `future` returns `Err(error)`, then it prints `error` to the console and then panics.
///
/// Otherwise if `future` returns `Ok(value)` then the output
/// [`Future`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.Future.html)
/// returns `value`.
///
/// See the documentation for [`spawn_local`](fn.spawn_local.html) for more details.
///
/// # Panics
/// It panics if `future` returns `Err`.
#[inline]
pub fn unwrap_future< F >( future: F ) -> impl Future< Output = F::Ok >
where F: TryFuture,
F::Error: JsSerialize {
future.unwrap_or_else( |x| print_error_panic( x ) )
}
/// Converts a JavaScript [`Promise`](struct.Promise.html) into a Rust
/// [`Future`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.Future.html).
///
/// The preferred way to create a `PromiseFuture` is to use [`value.try_into()`](unstable/trait.TryInto.html) on a
/// JavaScript [`Value`](enum.Value.html).
///
/// After creating a `PromiseFuture` you can use all of the
/// [`FutureExt`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.FutureExt.html)
/// and [`TryFutureExt`](https://rust-lang-nursery.github.io/futures-api-docs/0.3.0-alpha.5/futures/future/trait.TryFutureExt.html)
/// methods on it, and you can spawn it by using [`spawn_local`](fn.spawn_local.html).
///
/// # Examples
///
/// Convert a JavaScript `Promise` into a `PromiseFuture`:
///
/// ```rust
/// fn foo() -> PromiseFuture<String> {
/// js!( return Promise.resolve("foo"); ).try_into().unwrap()
/// }
/// ```
pub struct PromiseFuture< Value, Error = error::Error > {
pub(crate) future: Receiver< Result< Value, Error > >,
pub(crate) _done_handle: DiscardOnDrop< DoneHandle >,
}
impl< A, B > std::fmt::Debug for PromiseFuture< A, B > {
fn fmt( &self, formatter: &mut std::fmt::Formatter ) -> std::fmt::Result {
formatter.debug_struct( "PromiseFuture" ).finish()
}
}
impl< A, B > Future for PromiseFuture< A, B > {
type Output = Result< A, B >;
#[inline]
fn poll( mut self: Pin< &mut Self >, waker: &LocalWaker ) -> Poll< Self::Output > {
// TODO maybe remove this unwrap ?
self.future.poll_unpin( waker ).map( |x| x.unwrap() )
}
}
impl< A, B > TryFrom< Value > for PromiseFuture< A, B >
where A: TryFrom< Value > + 'static,
B: TryFrom< Value > + 'static,
// TODO remove this later
A::Error: std::fmt::Debug,
B::Error: std::fmt::Debug {
type Error = ConversionError;
fn try_from( v: Value ) -> Result< Self, Self::Error > {
let promise: Promise = v.try_into()?;
Ok( promise.to_future() )
}
}