Asynchronous Programming
Last updated
Last updated
We already covered basic threading in our core BoxLang section. In this section, we will cover the usage of asynchronous programming via futures and the runAsync()
function built into BoxLang.
A Future is an eventual result of an asynchronous operation.
This function returns a Future object, an asynchronous operation's eventual result. A representation of what the operation will produce in the future, it takes in two arguments and returns a BoxLang Future object.
callback:function
- Closure/Lambda function that returns a result to be resolved
timeout:numeric
- Timeout for the asynchronous process in milliseconds
The return of the runAsync()
function is a BoxLang Future, not a Java Future. The Future Object has the following functions available:
Function | ReturnType | Description |
---|---|---|
| Boolean | Cancel the operation |
| value | Sets a value to return from the future, usually from an empty future operation. |
| Future | Register an error callback that will be called if the async operation fails or the timeout is reached |
| Future | Register an error callback that will be called if the async operation fails |
| Any | The value of the async operation once it finalizes. Caution: This operation blocks until the async operation finalizes. |
| Any | The value of the async operation with a timeout in milliseconds. Caution: This operation blocks until the async operation finalizes. |
| Boolean | Verifies if the operation has been cancelled or not |
| Boolean | Verifies if the operation has finalized or not |
| Future | Once the first callback operation has finalized, call this secondary callback with the value of the previous operation and return another Future |
| Future | Once the first callback operation has finalized, call this secondary callback with the value of the previous operation and return another Future but with a timeout |
All timeouts are in milliseconds
With the future you can now create fluent functional programming constructs to deal with your async operation. You can create different error listeners and even continue processing the value the async operation produced in another asynchronous operation. It's much like a pipeline of never-ending futures!
Mix and match the callback functions to create a nice asynchronous pipeline. Just note that if you call the get()
operation immediately, that will BLOCK the execution until the async operation finalizes, which kind of defeats the purpose of the async operation. If you do not want to block, use the then()
approach where that callback will be called for you with the result of the async operation, and then you can do your post-processing. The alternative is to sit and poll the isDone()
or isCancelled()
operations, and YUCK!