Skip to Content
API reference

Promise

The eventual result of an asynchronous operation. An async TypeScript function returns a promise, and Java or Kotlin receives the same object.

AsyncType: typescriptnative.PromiseArtifact: com.margelo:typescript-native-stdlib

Type mapping

TypeScriptJVMNotes
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.

T
the fulfillment type; use Void with a null value for void

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.

executor
the operation to start synchronously

Static methods

static void setUnhandledRejectionHandler(UnhandledRejectionHandler handler)

Installs the host handler selected at report time. Null restores fatal termination.

handler
the host callback, or null to terminate on an unhandled rejection
static <V> Promise<V> pending(PromisePayload<V> origin)

Creates a pending producer with an explicit payload representation. Generated producers supply this descriptor.

V
the payload type
origin
the non-null producer representation
Returns
a new semantic Promise
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.

V
the declared native payload type
producer
the native producer handle
declared
the supported payload representation of its declared boundary signature
Returns
the matching original or cached native handle
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.

value
a Promise handle or any other value
Returns
the original native handle for a Promise, otherwise value itself
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.

V
the fulfillment type
value
the value, possibly null, or a promise to follow
Returns
a new promise resolved with the supplied value
static <V> Promise<V> rejected(Object reason)

Creates a rejected promise. An unobserved rejection requires a reporting owner.

V
the fulfillment type
reason
the original rejection object, possibly null for undefined; it is stored without wrapping or copying
Returns
a new promise rejected with the supplied reason
static Throwable exception(Object reason)

Carries a rejection through an exception-only API. This method returns an exception without throwing it.

reason
the original rejection object, possibly null for undefined
Returns
the same object if it is a Throwable, otherwise a new Rejection holding 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.

failure
the exception to convert, possibly null
Returns
the carrier's reason, or the same failure when it is not a carrier
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).

failure
the caught exception
Returns
the carrier's reason, or the same failure when it is not a carrier

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.

V
the consumer payload type
consumer
the supported consumer representation
Returns
the original or cached native handle
Throws IllegalStateException
if an opaque native producer has not been imported with fromNative
Object canonicalObject()
Returns
the single published AOT object, or null before first exposure
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.

candidate
the non-null branded object constructed for this root
Returns
the single published object, possibly another caller's candidate
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.

value
the value, possibly null, or a promise to follow
Returns
true if this call claimed the pending promise, false if it had already been claimed
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.

reason
the original rejection object, possibly null for undefined; it is stored without wrapping or copying
Returns
true if this call rejected the pending promise, false if it had already been claimed
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.

source
the non-null promise whose outcome to follow
Returns
true if this call claimed the pending promise, including self-rejection; false if already claimed
Throws NullPointerException
if source is null, even if this promise was already claimed
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.

then
the thenable's then
Returns
true if this call claimed the pending promise, false if it had already been claimed
Throws IllegalStateException
if the calling thread has no live execution owner, with nothing claimed
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.

owner
the non-null queue that will run the callback
handler
the non-null observer retained until disposal or execution
Returns
a subscription that can suppress this observation without cancelling the promise
Throws NullPointerException
if owner or handler is null
Throws IllegalStateException
if the owner has stopped, including when its host refuses the turn
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.

handler
the non-null observer retained until disposal or execution
Returns
a subscription for this observation; the callback may already have run when this returns
Throws NullPointerException
if handler is null
<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
the child's fulfillment type
success
the non-null fulfillment handler
Returns
a new child resolved with the handler's result, or rejected with its unwrapped failure
Throws NullPointerException
if success is null
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
<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
the child's fulfillment type
success
the non-null fulfillment handler
failure
the rejection handler, or null to pass the original rejection to the child
Returns
a new child resolved with the selected handler's result
Throws NullPointerException
if success is null
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
<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.

R
the child's fulfillment type
success
the handler returning a non-null promise; a null handler rejects the child on fulfillment
Returns
a new child that follows the handler's promise
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
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.

onRejected
the non-null recovery handler
Returns
a new child resolved with the recovery result, or rejected with its unwrapped failure
Throws NullPointerException
if onRejected is null
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
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.

failure
the handler returning a non-null promise; a null handler rejects the child on rejection
Returns
a new child that follows the recovery promise
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
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.

cleanup
the non-null cleanup action
Returns
a new child carrying the outcome after cleanup
Throws NullPointerException
if cleanup is null
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn
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.

cleanup
the non-null cleanup function, whose result may be null or a promise to wait for
Returns
a new child carrying the outcome after cleanup
Throws NullPointerException
if cleanup is null
Throws IllegalStateException
if the calling thread has no live execution owner or its host refuses the turn

Promise.Resolver interface

public interface Resolver<V>

The executor's handle for Promise.resolve. It may be retained and called from any thread.

V
the fulfillment type

Methods

void resolve(V value)

Fulfills the promise or starts following a promise value. Later settlement attempts have no effect.

value
the value, possibly null, or a promise to follow

Promise.Rejecter interface

public interface Rejecter

The executor's handle for Promise.reject. It may be retained and called from any thread.

Methods

void reject(Object reason)

Rejects the promise if no settlement or adoption has claimed it.

reason
the original rejection object, possibly null for undefined

Promise.Executor interface

public interface Executor<V>

Initializes a promise synchronously. Construction and fulfillment need no loop; rejection needs reporting setup.

V
the fulfillment type

Methods

void run(Resolver<V> resolve, Rejecter reject)

Starts the operation. Returning without using either handle leaves the promise pending.

resolve
the handle for fulfillment or adoption
reject
the handle for rejection
Throws Throwable
a failure that the constructor converts with Promise.reason and rejects with, unless a handle has already claimed the promise

Promise.Handler interface

public interface Handler<V, R>

A transformation run by a chaining method on the execution owner that registered it.

V
the input value or rejection type
R
the result type

Methods

R apply(V value)

Transforms an outcome. Chaining methods resolve or adopt the result into their child promise.

value
the fulfillment value or rejection reason
Returns
the result, possibly null; compose methods require a non-null promise
Throws Throwable
a failure used to reject the child after Promise.reason unwraps it

Promise.Action interface

public interface Action

A cleanup run by finallyDo on the execution owner that registered it.

Methods

void run()

Performs cleanup, preserving the original outcome on normal return.

Throws Throwable
a failure that replaces the original outcome, after Promise.reason

Promise.Cleanup interface

public interface Cleanup

A 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.

Returns
the promise to wait for, or null when there is no cleanup promise
Throws Throwable
a failure that replaces the original outcome, after Promise.reason

Promise.Subscription interface

public interface Subscription

The 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.

V
the fulfillment type

Methods

void fulfilled(V value)

Receives the fulfillment value.

value
the original value, possibly null
void rejected(Object reason)

Receives the rejection without converting it to an exception.

reason
the original rejection object, possibly null for undefined
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.

failure
the conversion failure, with no formatting of the original payload

Promise.Rejection class

public static final class Rejection extends RuntimeException

Carries a non-Throwable rejection through an API that only accepts exceptions.

Constructors

Rejection(Object reason)

Wraps a non-error rejection with the message Promise rejected.

reason
the original rejection object, possibly null for undefined
Rejection(Object reason, String message)

Carries a non-error value with text fixed at the throw.

reason
the original rejection object, possibly null for undefined
message
the carrier text

Fields

final Object reason

The original rejection object in the typed representation: Java null is undefined and Null.INSTANCE is null.

Promise.UnhandledRejectionHandler interface

public interface UnhandledRejectionHandler

A 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.

reason
the original object, possibly null for undefined
Throws Throwable
a handler failure that terminates the process

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.

V
the fulfillment type

Methods

void call(Resolvers<V> resolvers)

Calls the thenable's then with handles of which only the first call counts.

resolvers
the resolving handles of the following promise
Throws Throwable
a failure that rejects the promise after failureReason, unless a handle has already been used

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.

V
the fulfillment type

Methods

boolean resolve(V value)

Fulfills the promise with a value that is no promise. The value is converted to the storage representation.

value
the value, possibly null for undefined
Returns
true if this call settled the promise
boolean reject(Object reason)

Rejects the promise.

reason
the original rejection object, possibly null for undefined
Returns
true if this call rejected the promise
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.

source
the non-null promise to follow
Returns
true if this call passed the claim on
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.

then
the thenable's then, which the caller has read
Returns
true if this call passed the claim on
Throws IllegalStateException
if the calling thread has no live execution owner

Kotlin extensions Kotlin

Artifact: com.margelo:typescript-native-runtime-kotlin

Extension functions

awaitKotlinextension
suspend fun <T> Promise<T>.await(): T

Suspends 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.

Returns
the fulfillment value, including null when the promise fulfills with null
promiseKotlinextension
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.

block
the suspend operation launched in this scope
Returns
a new promise for the operation's result
voidPromiseKotlinextension
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.

block
the suspend operation launched in this scope
Returns
a new promise that fulfills with null or rejects with the operation's failure

Generated when the website builds, from Promise.java, PromiseCoroutines.kt.

Language

Remembered on every API page

On this page