Lambdas and exceptions
Ru | En
How create a lambda or a closure
- Make a lambda like in the usual JavaScript code.
- Don't declare any variables.
In a closure, we have access to the outside variables. Here, we read variable a. We will see this when we build the module and run the application.
18
There is an assignment in this lambda. We don't need to put a var keyword there because Drakon.Tech will declare the variable automatically. Keep in mind that the code generator will declare the variable in the containing function, not in the lambda. We can see it in the code.
function lambda() { var a, closure, foo, result; a = 10 closure = function (x) { foo = a + x return foo } result = closure(8) console.log(result) }
What about other JavaScript statements? Can we use if and for constructs inside lambdas in Drakon.Tech? Technically, it is possible but strongly discouraged. The presence of if and for constructs implies an algorithm with nontrivial control flow. Algorithms belong to flowcharts, not to lambdas.
What to do if we must have a complicated algorithm in a lambda?
- Move the algorithm in a separate function. Create a Drakon flowchart for that.
- Create a one-line lambda.
- Call that new function in the lambda.
Lambdas and closures bring tremendous expressive power, but that power comes at a cost. Every time the reader encounters a lambda in the code, they pay a significant mental price. Keep lambdas as short and straightforward as possible.
How to catch an exception
- Make a try-catch construct inside an Action icon like in the usual JavaScript code.
- Don't declare any variables.
All values assigned in a try-catch block will be available later in the function.
Here, the foo variable will keep its value outside of the try-catch block.
Do not put try-catch in async functions
Note that Drakon.Tech does not allow try-catch constructs in an async function. To catch exceptions in async functions, use the on error goto X feature as described here.