Async
Utils
SetTimeout
Spawns an asynchronous task (a wrapper over SchelduleTask), that evaluates an expression once
SetTimeout[expr_, interval_Real | interval_Quantity] _TaskObject
A symbol has HoldFirst attribute. An interval is in milliseconds. To cancel it, use
CancelTimeout[_TaskObject]
SetInterval
Spawns an asynchronous task (a wrapper over SchelduleTask), that evaluates an expression every interval milliseconds
SetInterval[expr_, interval_Real | interval_Quantity] _TaskObject
A symbol has HoldFirst attribute. To cancel this task use
TaskRemove[_TaskObject]
or
CancelInterval[_TaskObject]
PauseAsync
It works similar to Pause, but returns Promise
Then[PauseAsync[3], Beep];
TableAsync
It works similar to Table, but the inner expression can be implicit AsyncFunction
n = EvaluationCell[];
Then[TableAsync[
PauseAsync[1] // Await;
i
, {i,3}], CellPrint[#, "After"->n]&];
DoAsync
Works in the same way as TableAsync
More
Note, that there are more expressions in the standard library, which support patterns of async programming:
- FrontFetchAsync
- ChoiceDialogAsync
- SystemDialogInputAsync
ParallelSubmitAsyncParallelSubmitFunctionAsync- ExportAsync
- RasterizeAsync
DoAsyncTableAsyncPauseAsyncMMAViewAsyncAsyncFunction- Any
EventObject: InputButton and etc
Asynchronous Functions
AsyncFunction
It works similar to Function
AsyncFunction[args, body] _Promise
One can use it as normal function, but utilizing Await keyword. On the background it restructures body in the runtime.
Await
Holds the execution (non blocking to threads) until the promise is resolved and returns the result
Await[_ | _Promise] _
If the argument is not Promise it won't pause the execution and return the result without changes.
SetCompoundExpressionIfModule,With_Symbolor any other singular expressionsTableAsyncDoAsyncPauseAsync- any expression, that returns
PromiseorEventObject
What is not supported (by now)
- Loops:
While,For,Do - Tables and maps:
Map,Table Returnwill not work correctly insideAsyncFunction
For example:
btn = InputButton[]
Then[AsyncFunction[x, Module[{res},
Speak["Click to start"];
btn // Await;
Speak["Choose"];
res = ChoiceDialogAsync["Add 10?"] // Await;
If[res, x + 10, x]
]][10], Speak];