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
extern crate futures;
extern crate js_sys;
extern crate wasm_bindgen;
extern crate wasm_bindgen_futures;
use futures::{Async, Future, Poll};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
// Code + docs: https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen_futures/
/// A future that becomes ready after a tick of the micro task queue.
pub struct NextTick {
inner: JsFuture,
}
impl NextTick {
/// Construct a new `NextTick` future.
pub fn new() -> NextTick {
// Create a resolved promise that will run its callbacks on the next
// tick of the micro task queue.
let promise = js_sys::Promise::resolve(&JsValue::NULL);
// Convert the promise into a `JsFuture`.
let inner = JsFuture::from(promise);
NextTick { inner }
}
}
impl Future for NextTick {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
// Polling a `NextTick` just forwards to polling if the inner promise is
// ready.
match self.inner.poll() {
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(_) => unreachable!(
"We only create NextTick with a resolved inner promise, never \
a rejected one, so we can't get an error here"
),
}
}
}