Async
Utils
SetTimeout
Spawns an asynchronous task (a wrapper over ScheduledTask) that evaluates an expression once.
SetTimeout[expr_, interval_Real | interval_Quantity] _TaskObjectThis symbol has the HoldFirst attribute. The interval is specified in milliseconds or as a Quantity object. To cancel it, use:
CancelTimeout[_TaskObject]SetInterval
Spawns an asynchronous task (a wrapper over ScheduledTask) that evaluates an expression every interval milliseconds.
SetInterval[expr_, interval_Real | interval_Quantity] _TaskObjectThis symbol has the HoldFirst attribute. To cancel this task, use:
TaskRemove[_TaskObject]or
CancelInterval[_TaskObject]PauseAsync
Works similarly to Pause, but returns a Promise.
Then[PauseAsync[3], Beep];TableAsync
Works similarly to Table, but the inner expression can be an implicit AsyncFunction.
n = EvaluationCell[];
TableAsync[
PauseAsync[1] // Await;
i
, {i,3}] // WaitAllDoAsync
Works in the same way as TableAsync.
More
There are more expressions in the standard library that support async programming patterns:
- Any
EventObject: InputButton and etc - FrontFetchAsync
- ChoiceDialogAsync
- SystemDialogInputAsync
ParallelSubmitAsyncParallelSubmitFunctionAsync- ExportAsync
- RasterizeAsync
- Any symbol named as
*Async
Asynchronous Functions
AsyncFunction
Works similarly to Function.
AsyncFunction[args, body] _PromiseYou can use it as a normal function while utilizing the Await keyword. Behind the scenes, it restructures the body at runtime.
Await
Pauses execution (non-blocking to threads) until the promise is resolved and returns the result.
Await[_ | _Promise] _If the argument is not a Promise, execution continues without pausing and the argument is returned unchanged.
Supported expressions:
SetCompoundExpressionIfModule,With_Symbolor any other singular expressionsTableAsyncDoAsyncPauseAsync- Any expression that returns
PromiseorEventObject
Not yet supported:
- Loops:
While,For,Do Awaitinside the first argument ofWith- Tables and maps:
Map,Table Returndoes 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];