Skip to main content

Promise

Promise

A constructor and also representation of EventObject which can be fired only once (aka resolved) and even before a corresponding handler is attached

Promise[] _Promise (* constructor *)

To resolve or reject a promise - use EventFire

EventFire[p_Promise, Resolve | Reject, data_]

Then

An expression for asynchronous subscribing to promise resolution or rejection

Then[p_Promise | _List | _, resolve_]
Then[p_Promise | _List | _, resolve_, reject_]

where resolve and reject are any arbitrary functions. This is non-blocking function.

info

The key difference between EventHandler and Then is that Then can even be applied to already resolved Promise object (after it was fired), which will cause an immediate evaluation of resolve or reject functions.

Being applied to a List of _Promise objects it will wait until all of them are resolved before evaluating resolve function.

Any Wolfram Expressions, which is not a List or Promise counts as resolved.

Example

Let's try with a multiple promise events

p1 = Promise[];
p2 = Promise[];

SetTimeout[EventFire[p1, Resolve, Null], 1000];
SetTimeout[EventFire[p2, Resolve, Null], 1500];

Then[{p1,p2,Null}, Function[Null,
Echo["Resolved!"];
]];

Here Null as a last element of a list was used just for demonstration purposes. It can also be any non _Promise | _List expression.

WaitAll

A synchronous blocking function to wait until a promise has resolved and returns the result

WaitAll[p_Promise] _

There is a timeout of 5 seconds, then $Failed is returned.

caution

Be careful while using this. Avoid to use in SessionSubmit, BackgroundTask and other interrupting the main loop subroutines. If your promise resolution does depend on TCP socket message, it will never be resolved properly, since all subroutines blocks TCP sockets and other external services.