Asynchronous Programming
DotHRB provides support for asynchronous operations using the Async/Await and Promises paradigm, similar to JavaScript. This allows your application to perform non-blocking tasks, significantly improving responsiveness and efficiency when dealing with operations like network requests or long calculations.
1. Core Asynchronous Functions
These functions handle the fundamental creation and blocking of asynchronous tasks.
| Function | Signature/Syntax | Description |
|---|---|---|
async | hPromise := async(bTask) | Creates a Promise. Executes the given code block (bTask) asynchronously and immediately returns a Promise Handle (hPromise). |
await | xResult := await(hPromise) | Awaits Resolution. Blocks execution of the current function until the specified promise (hPromise) is either resolved (completed successfully) or rejected (failed). Returns the result or throws an error. |
2. Promise Chains (Handling Results and Errors)
These methods allow you to attach callback functions to handle the outcome of a promise without blocking the current thread.
| Function | Example Syntax | Description |
|---|---|---|
promiseThen | promiseThen( hPromise, {|result| ...} ) | Attaches a success callback. Executes the provided code block only if the hPromise is resolved. The block receives the successful result. |
promiseCatch | promiseCatch( hPromise, {|oError| ...} ) | Attaches an error handler. Executes the provided code block only if the hPromise is rejected (failed). The block receives the error object (oError). |
Example: Chaining Then and Catch
Promises can be easily chained to define a complete flow:
promiseCatch(
promiseThen(
async( {|| longCalcTask() } ), ; // Start async task
{|result| execThisWhenPromiseOk( result) } ; // Success handler
), ;
{|oError| execThisWhenPromiseError( oError ) } ; // Failure handler
)
3. Handling Multiple Promises
These utilities are essential for coordinating multiple concurrent asynchronous tasks.
| Function | Example Syntax | Description | |
|---|---|---|---|
promiseAll | aResults := promiseAll( {hP1, hP2} ) | Aggregates Results. Takes an array of promises (aPromises). Returns a single new Promise that resolves only when all input promises have successfully resolved. The result is an array of all individual results. | |
promiseWaitAll | promiseWaitAll(nTimeOut) | Wait with Timeout. Blocks the current thread, waiting for all currently running background promises to complete, up to the specified nTimeOut limit (in milliseconds). |