Promise
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Promise
A constructor and also a derived class of EventObject which can be fired only once (aka resolved or rejected) even before a corresponding event 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, usually, non-blocking functions.
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 and will return the list of results.
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] _WaitAll[p_Promise, timeout_:15] _There is a timeout of 15 seconds, then $Failed is returned.
WaitAll is a blocking function. Avoid to use in SessionSubmit, BackgroundTask, or any other event handlers or asynchronous functions!