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_]
Promise is actively used in async functions. See more at Async
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.
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 of Promise counts as resolved, i.e. this is valid
Then[1+1, Function[result, Print]];
p = Promise[];
Then[{1+1, p}, Function[result, Print]];
Pause[3];
EventFire[p, Resolve, 43];
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.
Relation to EventObject
Then[e_EventObject, resolve_]
It effectively assigns an event handler to e and calls resolve on any pattern captured.
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.
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.