pub struct Promise(pub Rc<RefCell<PromiseData>>);Expand description
A single-assignment value that may not be available yet.
A promise is pending until Promise::resolve gives it a value, and
resolved afterwards. Callbacks registered with Promise::then run when
it resolves.
- Resolve once. The first call to
resolvewins; later calls are ignored. - Never rejects. There is no failure state. Resolving with
Value::UndefinedstoresValue::Nothinginstead. - Synchronous dispatch. Callbacks run on the caller’s stack, inside
resolve(if registered while pending) or insidethen(if already resolved). There is no scheduler in this crate. - Shared identity.
Promiseis a cheap handle: clones observe the same resolution. - No flattening. If a callback returns a
Value::Promise, the child promise resolves to that promise; it is not unwrapped.
The inner Rc<RefCell<PromiseData>> is public so that hosts can inspect
the state; prefer then and resolve to change it.
§Examples
use swan_core::value::{Promise, Value};
let p = Promise::new();
let child = p.then(|v| match v {
Value::Numb(n) => Value::Numb(n + 1.0),
other => other,
});
p.resolve(Value::Numb(41.0));
if let Value::Promise(child) = child {
assert_eq!(child.0.borrow().value, Some(Value::Numb(42.0)));
}Tuple Fields§
§0: Rc<RefCell<PromiseData>>Implementations§
Source§impl Promise
impl Promise
Sourcepub fn then(&self, f: impl Fn(Value) -> Value + 'static) -> Value
pub fn then(&self, f: impl Fn(Value) -> Value + 'static) -> Value
Registers a Rust callback and returns a child promise (as Value::Promise)
that resolves to the callback’s result.
- If
selfis already resolved,fis called immediately with a clone of the value and the returned child is already resolved. - If
selfis pending,fis queued and runs whenselfis resolved.
f is invoked at most once. If f returns Value::Undefined, the child
resolves to Value::Nothing (see Promise::resolve).
Sourcepub fn then_apply(&self, f: Value, pos: usize) -> Value
pub fn then_apply(&self, f: Value, pos: usize) -> Value
Like Promise::then, but takes a Swan callable instead of a Rust closure.
The callable f is applied to the resolved value via
eval_apply, with pos as the source position used in any resulting
Undefined (for example, when f is not callable). Such an Undefined
result resolves the child to Value::Nothing.
Sourcepub fn resolve(&self, v: Value)
pub fn resolve(&self, v: Value)
Resolves this promise with v and runs all queued callbacks.
- Only the first call has any effect; if the promise is already resolved,
vis ignored and nothing runs. Value::Undefined(_)is replaced byValue::Nothing, so a promise never holds an undefined value.- Each queued callback is called in registration order with a clone of the resolved value, and its result resolves the associated child promise. Resolution therefore cascades down the chain synchronously.
- The internal borrow is released before callbacks run, so callbacks may
safely call
thenon this promise (they will see it already resolved).