Promise
The eventual result of an asynchronous operation. An async TypeScript function returns a promise, and Java or Kotlin receives the same object.
typescriptnative.PromiseArtifact: com.margelo:typescript-native-stdlibType mapping
| TypeScript | JVM | Notes |
|---|---|---|
Promise<T> | typescriptnative.Promise<T> | The same object on both sides. |
Promise<void> | Promise<Void> | A void result appears as Void in Java. |
Promise class
public final class Promise<T>A single settlement with ordered asynchronous reactions. Void fulfills with null.
Construction and fulfillment need no event loop. An unobserved rejection needs a reporting owner, captured at construction or, for an ownerless creation, at rejection. Each reaction separately belongs to the JobQueue of the thread that registered it with then, or to the queue passed to observeOn. A reaction runs as a job of that queue, in a later turn of its host loop, never inside then, resolve or reject and never while a promise lock is held. Any thread may settle a promise. Reactions of one promise that belong to one queue run in the order of their registration. Native adapters can also observe without an owner through observe; those observers may run inline.
A rejection reason is a TypeScript unknown in the typed representation (#687): Java null is undefined and Null.INSTANCE is null, in reject, Rejection.reason, observers and the unhandled rejection handler.
Constructors
Promise()Creates a native producer; its first import must declare its producer's supported payload signature.
Promise(Executor<T> executor)Creates a promise and calls executor immediately on the calling thread. Construction and fulfillment need no event loop. An unobserved rejection needs a reporting owner; a missing-owner setup failure propagates outside the executor catch with its raw reason as cause, rather than being swallowed by first-settlement-wins. The handles may be kept for later calls from any thread. The first settlement or adoption wins. A thrown failure is converted with reason and offered as a rejection; it has no effect after a handle wins. A null executor is caught as a NullPointerException rejection too.
Static methods
static void setUnhandledRejectionHandler(UnhandledRejectionHandler handler)Installs the host handler selected at report time. Null restores fatal termination.
static <V> Promise<V> pending(PromisePayload<V> origin)Creates a pending producer with an explicit payload representation. Generated producers supply this descriptor.
static <V> Promise<V> fromNative(Promise<V> producer, PromisePayload<V> declared)Imports an opaque native producer using its declared producer signature, before widening it. On the original handle this establishes its ABI independently of any storage origin inherited during adoption. Existing ABI and storage declarations remain unchanged; subsequent signatures select consumer views. No value determines erased T.
static Object identity(Object value)Normalizes native Promise handles for source identity operations. Other values pass through unchanged. Java equals/hashCode and Java reference equality retain their usual meaning.
static <V> Promise<V> resolved(V value)Creates a promise and resolves it with value. No event loop is required. A promise value is followed, so the result need not be fulfilled when this method returns.
static <V> Promise<V> rejected(Object reason)Creates a rejected promise. An unobserved rejection requires a reporting owner.
static Throwable exception(Object reason)Carries a rejection through an exception-only API. This method returns an exception without throwing it.
static Object reason(Throwable failure)Unwraps one Rejection carrier, preserving its payload's identity. The result is an unknown value in the typed representation, as every rejection reason is: Java null is undefined and Null.INSTANCE is null. A Rejection of undefined, and a null failure, both return Java null. No value is converted.
static Object failureReason(Throwable failure)reason for a catch inside a Promise operation, such as the one around an executor, which rejects with what it caught. A failed reporting precondition (an unobserved rejection without a reporting owner) is not a reason: it propagates unchanged instead of becoming a second, ignored settlement. The JavaScript Promise of compiled packages uses it in its built-ins (#208).
Methods
<V> Promise<V> view(PromisePayload<V> consumer)Selects a consumer representation of an explicitly described Promise. Equivalent descriptors from independent graphs share a handle. Returning to the original ABI recovers the original Java reference, even when adoption selected different settlement storage. Different payload views have different Java references and the same semantic identity. View selection never establishes the producer's ABI or storage origin.
Object canonicalObject()Object publishCanonicalObject(Object candidate)Publishes a preconstructed AOT object, retaining it strongly for the root's lifetime. Construction, getters and codecs belong before this call. Losing concurrent candidates are discarded by the caller. No global table retains the root, and no work occurs under the settlement lock.
boolean resolve(T value)Claims this pending promise for fulfillment or adoption. May be called from any thread without an event loop. A non-promise value is converted to the storage representation when needed. A promise value is followed as in adopt; resolving to this promise itself rejects it with an IllegalStateException.
Once claimed, later resolve and reject calls, and adopt calls with a non-null source, return false and preserve the chosen outcome or source. Payload conversion reserves the pending promise while it runs. If conversion throws, that reservation is released and the same failure escapes; a fresh attempt may retry. For example, new Promise<Integer>().resolve(3) returns true; rejecting that same promise later returns false and its fulfillment remains 3. True means the claim succeeded, not that any reaction has run or that an adopted source has settled. Owned reactions run later; an observer without an owner may run before this returns.
boolean reject(Object reason)Claims this pending promise for rejection from any thread. Without accepted observation it uses its creator's reporting owner, or captures the current live owner if it had none. Without either it throws a setup failure preserving the original reason as its cause through exception. Later settlement attempts have no effect, including when this promise is already following a source. Owned reactions run later; an observer without an owner may run before this returns.
boolean adopt(Promise<? extends T> source)Claims this pending promise to follow source, preserving its fulfillment value or rejection reason. Later settlement attempts cannot replace the source. Following this promise itself rejects it with an IllegalStateException; indirect adoption cycles can stay pending.
Any thread may call this. On an execution owner, a first job subscribes and a later source reaction settles this promise on that owner's queue. Without an owner, forwarding needs no event loop and can settle this promise before this call returns. If the owner's loop refuses adoption work, forwarding falls back to an observation without an owner. Adoption does not cancel or take exclusive ownership of the source.
boolean followThenable(Thenable<T> then)Follows a thenable whose then the caller has read (#181): this pending promise is claimed, and one job of the calling thread's owner calls then with new resolving handles, NewPromiseResolveThenableJob in ECMAScript. A thenable that resolves at once settles the promise one job later, two jobs in all. A throw from then rejects, unless a handle has been used. When the owner's loop refuses the job, the promise rejects with that failure, and then is never called.
Subscription observeOn(JobQueue owner, Observer<? super T> handler)Registers a reaction that runs as a job of owner, after the reactions that were registered for that queue before it. An async function resumes this way on the owner that it captured when it started. Throws IllegalStateException, with nothing registered, when the host loop of the owner has stopped.
Other host failures during registration propagate unchanged.
A payload view converts fulfillment in this delivery, outside the root lock. A conversion failure calls Observer.conversionFailed separately from source rejection. Observer exceptions retain the task-error path. Conversion never changes the source outcome or another consumer's representation.
Subscription observe(Observer<? super T> handler)Registers an observer for native adapters that hand the outcome on, such as a CompletableFuture or a coroutine continuation. On a thread that is an execution owner it is a job of that owner, like a reaction. On any other thread it has no owner: it is called on the thread that settles the promise, after the settlement, or at once on the calling thread when the promise has already settled. If owner registration fails, it falls back to this unowned delivery, which may run inline even while the owner remains live. A failure from a still-live host is reported before the fallback. It never fails for a missing event loop.
A payload view converts fulfillment in this delivery, outside the root lock. A conversion failure calls Observer.conversionFailed separately from source rejection. Observer exceptions retain the task-error path. Conversion never changes the source outcome or another consumer's representation.
<R> Promise<R> then(Handler<? super T, ? extends R> success)Maps fulfillment on the calling thread's execution owner, passing rejection unchanged to the child.
Other host failures during registration propagate unchanged.
<R> Promise<R> then(Handler<? super T, ? extends R> success, Handler<Object, ? extends R> failure)Maps an outcome in a later job of the calling thread's execution owner. Only the handler matching the outcome runs. A returned promise is followed; a thrown failure rejects the child after reason.
Other host failures during registration propagate unchanged.
<R> Promise<R> thenCompose(Handler<? super T, ? extends Promise<? extends R>> success)Follows the promise returned by a fulfillment handler in a later job of the calling thread's execution owner. A source rejection passes unchanged to the child. A thrown failure, including returning null instead of a promise, rejects the child after reason.
Other host failures during registration propagate unchanged.
Promise<T> catchError(Handler<Object, ? extends T> onRejected)Maps rejection in a later job of the calling thread's execution owner, preserving fulfillment unchanged.
Other host failures during registration propagate unchanged.
Promise<T> catchCompose(Handler<Object, ? extends Promise<? extends T>> failure)Follows a recovery promise in a later job of the calling thread's execution owner, preserving fulfillment unchanged. A thrown failure, including returning null, rejects the child after reason.
Other host failures during registration propagate unchanged.
Promise<T> finallyDo(Action cleanup)Runs cleanup for either outcome in a later job of the calling thread's execution owner. Normal return preserves the original outcome; a thrown failure replaces it after reason.
Other host failures during registration propagate unchanged.
Promise<T> finallyCompose(Cleanup cleanup)Runs cleanup for either outcome on the calling thread's execution owner and waits for its promise. Fulfillment of that promise preserves the original outcome; rejection replaces it. A null result needs no cleanup promise, but restoration still runs in a later job. A thrown failure replaces the outcome after reason. Returning the child itself creates an indirect cycle that stays pending.
Other host failures during registration propagate unchanged.
Promise.Resolver interface
public interface Resolver<V>The executor's handle for Promise.resolve. It may be retained and called from any thread.
Methods
void resolve(V value)Fulfills the promise or starts following a promise value. Later settlement attempts have no effect.
Promise.Rejecter interface
public interface RejecterThe executor's handle for Promise.reject. It may be retained and called from any thread.
Methods
Promise.Executor interface
public interface Executor<V>Initializes a promise synchronously. Construction and fulfillment need no loop; rejection needs reporting setup.
Methods
void run(Resolver<V> resolve, Rejecter reject)Starts the operation. Returning without using either handle leaves the promise pending.
Promise.Handler interface
public interface Handler<V, R>A transformation run by a chaining method on the execution owner that registered it.
Methods
R apply(V value)Transforms an outcome. Chaining methods resolve or adopt the result into their child promise.
Promise.Action interface
public interface ActionA cleanup run by finallyDo on the execution owner that registered it.
Methods
Promise.Cleanup interface
public interface CleanupA cleanup run by finallyCompose on the execution owner that registered it.
Methods
Promise<?> run()Starts cleanup. Its fulfillment preserves the original outcome; its rejection replaces it.
Promise.Subscription interface
public interface SubscriptionThe lifetime of one observation, independent of the promise and its other consumers.
Methods
void dispose()Releases the observer and prevents a callback that has not yet been taken for execution. This is safe from any thread and repeated calls do nothing. It cannot interrupt a callback already taken for execution. Disposing does not settle the promise, cancel its producer or affect other observations.
Promise.Observer interface
public interface Observer<V>Receives one original outcome through observe or observeOn. The registration method determines the callback's thread and timing. Disposal or a stopped owner can prevent delivery; the observer is released when disposed or taken for execution. A callback failure is reported through the queue's error reporting, without changing the observed promise or creating a rejected child.
Methods
default void conversionFailed(Throwable failure)Receives a failure to convert a successful payload for this consumer. This is separate from a source rejection. Native observers default to their failure path; chaining operations override it to reject their child without invoking the source-rejection handler. An exception thrown by this method is an observer error.
Promise.Rejection class
public static final class Rejection extends RuntimeExceptionCarries a non-Throwable rejection through an API that only accepts exceptions.
Constructors
Fields
final Object reasonThe original rejection object in the typed representation: Java null is undefined and Null.INSTANCE is null.
Promise.UnhandledRejectionHandler interface
public interface UnhandledRejectionHandlerA host-wide raw rejection callback. Returning permits the owner to continue.
Methods
void rejected(Object reason)Receives the original reason without formatting or carrier conversion.
Promise.Thenable interface
public interface Thenable<V>A thenable that is not a promise of this runtime, such as an object of JavaScript whose then the caller has read. Its job calls it with the resolving handles of the promise that follows it.
Methods
void call(Resolvers<V> resolvers)Calls the thenable's then with handles of which only the first call counts.
Promise.Resolvers class
public static final class Resolvers<V>The resolving handles that a thenable job passes to Thenable.call. They hold the claim of the promise that follows the thenable: only the first call of any of them counts, from any thread. Their caller classifies a value first, as package JavaScript does: a promise is adopted, another thenable is followed, anything else fulfills.
Methods
boolean resolve(V value)Fulfills the promise with a value that is no promise. The value is converted to the storage representation.
boolean adopt(Promise<? extends V> source)Follows another promise, in two jobs of the calling thread's owner, or on its settling thread without one.
boolean follow(Thenable<V> then)Follows another thenable in a job of the calling thread's owner. Without a live owner this throws and uses nothing.
Kotlin extensions Kotlin
Artifact: com.margelo:typescript-native-runtime-kotlin
Extension functions
suspend fun <T> Promise<T>.await(): TSuspends until the promise settles. It needs no event loop on the calling thread: the coroutine resumes through its own dispatcher. The resumption never runs inside the call that settles the promise, also when the dispatcher has an immediate path (Dispatchers.Main.immediate). One kind of dispatcher cannot be deferred: one that runs blocks inside dispatch, which is Dispatchers.Unconfined and an executor that runs its task in the calling thread (Executor { it.run() }.asCoroutineDispatcher()). On a thread that is no execution owner such a coroutine resumes inside the call that settles the promise. Cancelling this waiter removes its observer; other consumers can still use the same promise. Cancellation does not settle the promise or cancel its producer. Rejection resumes with Promise.exception: a Throwable is thrown through the continuation, and any other reason, including null, is held in Promise.Rejection. Coroutine exception recovery can copy a Throwable and retain its original as a cause.
fun <T> CoroutineScope.promise(block: suspend CoroutineScope.() -> T): Promise<T>The scope owns the underlying suspend operation and its dispatcher. Cancelling the scope cancels that operation and rejects the promise. Each reaction has its own execution owner. Unobserved rejection uses a separate reporting owner, captured from a live owner at creation or at rejection. Call this adapter on a supported owner if rejection can precede an accepted observation. Pending construction, fulfillment and observation-first worker settlement need no event loop on the settling thread. The operation is launched in this scope and settles the promise when it completes, after its cleanup has run. A failure is converted with Promise.reason. Settling the returned promise independently, or cancelling a coroutine awaiting it, does not cancel the launched operation. The first settlement or adoption still wins. Called inside EventLoop.run, this producer keeps that run alive through completion and settlement.
fun CoroutineScope.voidPromise(block: suspend CoroutineScope.() -> Unit): Promise<Void?>Launches a suspend operation with the ownership and cancellation rules of promise. Promise<void> uses java.lang.Void and fulfills with null after the block completes normally.
Generated when the website builds, from Promise.java, PromiseCoroutines.kt.