LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class Promise<T>

A value that arrives later.

since 0.1.0-alpha.1linuxwindows

Overview

A promise starts out pending and is settled exactly once, by resolve with a value or by reject with an exception. await promise waits, without blocking the rest of the program, until the promise is ready and then gives its value; if the promise is already ready, await returns at once. If the promise was rejected, await throws the exception it was rejected with, so a catch selects it by class exactly as for an ordinary throw. Any function may await, because there is no separate async function type: a function that returns a Promise<T> is simply the asynchronous form. A promise that only signals completion is a Promise<void>, resolved with resolve(None).

Create a pending promise with Promise() and a ready one with Promise(value). Something else, usually a timer or a callback, calls resolve when the value exists, or reject when it never will. A rejection that nothing ever awaits is reported when the program's event loop runs out of work, as an uncaught exception.

Description

Promise<T> is an ordinary class. The language gives it no special rules and wraps nothing for you: a function that is meant to produce a value later must return a real Promise, and the body of such a function is responsible for resolving it. await is the one operation the language treats specially, and it only needs something promise-shaped to wait on.

A promise is created in one of two states.

  • Promise() is pending: it holds no value yet. isReady() is false.
  • Promise(v) is pre-resolved: it already holds v. isReady() is true.

resolve(v) stores a value and marks the promise ready. get() reads the stored value, and then(cb) registers a callback to run with the value. If the promise is already ready, then runs the callback immediately; otherwise the callback runs inside the call to resolve that settles the promise.

reject(e) settles the promise with a failure instead: it becomes ready and failed, holding the exception e. isFailed() tells whether that happened, and the failure field holds e. await p and p.get() on a rejected promise throw e itself — the same object reject received, with its class — so catch selects it by type exactly as for an ordinary throw. A then callback never runs on a rejected promise.

Pending and pre-resolved promises

use io::console;

Promise<int> ready = Promise(42);
console.writeln(ready.isReady());
console.writeln(ready.get());

Promise<string> later = Promise();
console.writeln(later.isReady());
later.then((s) => console.writeln("then saw ${s}"));
console.writeln("resolving");
later.resolve("hello");
console.writeln(later.isReady());
true
42
false
resolving
then saw hello
true

A promise whose only job is to say "this has finished" is a Promise<void>. Resolve it with the unit value, None: done.resolve(None). A pre-resolved completion promise is Promise(None). Awaiting a Promise<void> waits but yields no usable value.

Rules

  • A function that returns a promise must return a real Promise; there is no implicit wrapping of plain values and no async keyword.
  • await expr unwraps a Promise<T> to a T. An await on a promise that is already ready does not suspend at all. See lang.await for what runs while an await waits.
  • then holds one callback. Calling then on a pending promise a second time replaces the first callback instead of adding to it.
  • A promise settles exactly once, by resolve(v) or reject(e). isReady() is true after either; isFailed() only after reject. A second settle of any kind — resolve after resolve, reject after resolve, and so on — throws RuntimeException("promise already settled") and changes nothing.
  • Observing a rejection. await p and p.get() on a rejected promise throw the stored exception object (not a copy, not a RuntimeException wrapper) and count as handling it. isReady(), isFailed(), reading failure and registering then do not.
  • then is for values only. On a rejected promise its callback never runs, and a callback still pending when reject is called is dropped. There is no .catch(): handle a rejection with await inside try.
  • An unobserved rejection is an uncaught exception. When the event loop runs out of work and some rejection was never awaited or get()-ed, the program ends as if the first such exception (in rejection order) had been thrown and not caught: Uncaught <Class>: <message>, exit status 1. Only the first is reported. A program that ends by env::exit(n) reports nothing. Inside a worker body, an unobserved rejection makes the worker fail with that exception when the body finishes, so it arrives at the await that joins it.
  • then runs its callback synchronously, in the context of whoever resolves the promise. If you need to wait in straight-line code, use await.

Examples

A function that returns a promise, resolved by a timer and consumed with await:

Awaiting a promise resolved by a timer

use io::console;
use std;

Promise<int> square(int n) {
    Promise<int> p = Promise();
    std::sysTimerStart(5, 0, (t) => p.resolve(n * n));
    return p;
}
int sq = await square(7);
console.writeln("7 squared is ${sq}");

Promise<int> already = Promise(9);
console.writeln(await already);
console.writeln(await 5);
7 squared is 49
9
5

The last line shows that await on a value that is not a promise yields the value unchanged.

Rejecting a promise with an exception of your own class, and catching it by that class at the await. A second settle throws:

Rejecting a promise

use io::console;
use std;

class LookupError : Exception {
    string key;
    new LookupError(string k) { Exception::Exception("no entry for ${k}"); key = k; }
}
Promise<string> find(string k) {
    Promise<string> p = Promise();
    std::sysTimerStart(5, 0, (t) => p.reject(LookupError(k)));
    return p;
}
Promise<string> found = find("color");
try {
    string v = await found;
    console.writeln(v);
} catch (LookupError e) {
    console.writeln("${e.message} (key ${e.key})");
}
console.writeln(found.isFailed());
try {
    found.resolve("late");
} catch (RuntimeException e) {
    console.writeln(e.message);
}
no entry for color (key color)
true
promise already settled

Notes

A Worker<T>, the handle returned by std::spawn, is itself a Promise<T>, so joining a worker is just an await. If the worker's body throws, spawn rejects the worker with the body's exception object, so the await that joins it throws that exception with its class.

Examples

Waiting for a value that a timer provides

use io::console;
use std;

Promise<int> done = Promise();
done.then((v) => { console.writeln("then saw ${v}"); });
console.writeln("ready? ${done.isReady()}");
done.resolve(7);
console.writeln("ready? ${done.isReady()}");
Promise<int> later = Promise();
std::sysTimerStart(10, 0, (n) => { later.resolve(99); });
int v;
v = await later;
console.writeln("awaited ${v}");
ready? false
then saw 7
ready? true
awaited 99

Constructors

new

new()

Create a pending promise.

The promise is not ready until something calls resolve or reject on it.

Examples

Pending and already-resolved promises

use io::console;

Promise<int> pending = Promise();
console.writeln(pending.isReady());
Promise<int> done = Promise(5);
console.writeln(done.isReady());
console.writeln(done.get());
false
true
5
new(T v)

Create a promise that is already resolved with a value.

Awaiting it returns the value at once, and then runs its callback immediately.

Parameters

v
The value the promise holds.

Fields

failed

bool failed

Whether the promise was settled by reject. Prefer isFailed.

failure

late IException failure

The exception given to reject, set only when failed is true; reading it before then raises a RuntimeException. Reading it does not count as handling the rejection.

ready

bool ready

Whether the promise has been settled, by resolve or reject. Prefer isReady.

value

late T value

The settled value, set by resolve. Reading it before the promise is resolved raises a RuntimeException. Prefer get or await.

Methods

get

get() -> T

Read the promise's value without waiting.

The value is only meaningful after the promise is ready; check isReady first, or use await to wait for it. On a rejected promise get throws the exception it was rejected with, exactly as await does.

Returns

The settled value.

Throws

IException
when the promise was rejected: the exception it was rejected with.

Examples

use io::console;

Promise<int> p = Promise(42);
if (p.isReady()) {
    console.writeln(p.get());
}
Promise<int> q = Promise();
q.reject(RuntimeException("lost"));
try {
    console.writeln(q.get());
} catch (RuntimeException e) {
    console.writeln("get threw: ${e.message}");
}
42
get threw: lost

isFailed

isFailed() -> bool

Tell whether the promise was settled by reject.

Checking it does not count as handling the rejection; only await or get does.

Returns

true once the promise has been rejected, otherwise false.

Examples

use io::console;

Promise<int> ok = Promise(1);
console.writeln(ok.isFailed());
Promise<int> bad = Promise();
bad.reject(RuntimeException("no route"));
console.writeln(bad.isFailed());
console.writeln(bad.failure.message);
try {
    bad.get();
} catch (RuntimeException e) {
    console.writeln("handled");
}
false
true
no route
handled

isReady

isReady() -> bool

Tell whether the promise has been settled.

Returns

true once the promise has been resolved or rejected, otherwise false.

Examples

use io::console;

Promise<int> p = Promise();
console.writeln(p.isReady());
p.resolve(1);
console.writeln(p.isReady());
false
true

reject

reject(IException e) -> void

Settle the promise with a failure.

The promise becomes ready and failed, holding e. Anything awaiting it wakes up, and await (or get) then throws e itself, with its class, so a catch selects it exactly as for an ordinary throw. A callback registered with then is dropped and never runs. A promise settles only once: rejecting or resolving it again throws a RuntimeException and leaves it as it was. A rejection that is never awaited is reported as an uncaught exception when the event loop runs out of work.

Parameters

e
The exception that await rethrows.

Throws

RuntimeException
when the promise was already settled.

Examples

use io::console;

class QuotaError : Exception {
    int limit;
    new QuotaError(string m, int l) { Exception::Exception(m); limit = l; }
}
Promise<int> p = Promise();
p.reject(QuotaError("over quota", 5));
try {
    int n = await p;
} catch (QuotaError e) {
    console.writeln("${e.message} (limit ${e.limit})");
}
over quota (limit 5)

resolve

resolve(T v) -> void

Settle the promise with a value.

The promise becomes ready, anything awaiting it wakes up, and the callback given to then runs with the value. For a Promise<void> resolve with None. A promise settles only once: resolving or rejecting it again throws a RuntimeException and leaves it as it was.

Parameters

v
The value to settle the promise with.

Throws

RuntimeException
when the promise was already settled.

Examples

use io::console;

Promise<string> p = Promise();
p.then((s) => { console.writeln("got ${s}"); });
p.resolve("hello");
console.writeln(p.get());
try {
    p.resolve("again");
} catch (RuntimeException e) {
    console.writeln(e.message);
}
Promise<void> signal = Promise();
signal.resolve(None);
console.writeln(signal.isReady());
got hello
hello
promise already settled
true

then

then((T) => void cb) -> void

Run a callback with the value once the promise is resolved.

If the promise is already resolved the callback runs immediately. Otherwise it runs inside resolve, in the context of whoever resolves the promise. A promise keeps only one callback: registering a second one before the promise is resolved replaces the first. On a rejected promise the callback never runs, and a callback still waiting when the promise is rejected is dropped; handle a rejection with await inside try instead.

Parameters

cb
The function to call with the value.

Examples

use io::console;

Promise<int> p = Promise();
p.then((v) => { console.writeln("first ${v}"); });
p.then((v) => { console.writeln("second ${v}"); });
p.resolve(1);
p.then((v) => { console.writeln("late ${v}"); });
Promise<int> q = Promise();
q.then((v) => { console.writeln("never runs"); });
q.reject(RuntimeException("cancelled order"));
q.then((v) => { console.writeln("never runs either"); });
try {
    int n = await q;
} catch (RuntimeException e) {
    console.writeln("rejected: ${e.message}");
}
second 1
late 1
rejected: cancelled order

See also

  • Worker — The handle to a value that another worker is computing.
  • awaitTimeout — Wait for a promise, but give up after a time limit.
  • Timer — A source of ticks on the event loop.
  • InStream — The reading end of a stream: a queue of values of type T that something else produces.