reto-js
v1.1.1
Published
Return from outer functions.
Downloads
4
Readme
reto-js
Usage
(() => {
(() => {
(() => {
// Imagine you need to return a value as a result of
// the outermost function right from here
})();
// and make sure that this
})();
// and this areas of code will not be reached.
})();
Of course there is a solution: use one more variable
(() => {
var tmp;
(() => {
(() => {
tmp = "foo";
return;
})();
if (typeof tmp != 'undefined') {
return;
}
// unreachable if `tmp` is set
})();
if (typeof tmp != 'undefined') {
return;
}
// unreachable if `tmp` is set
})();
but the code seems a little messy now.
reto-js
allows to do it in a more elegant manner:
$label('example', () => {
(() => {
(() => {
$return('example', 'some_value');
})();
})();
});
How it works
$return
throw
s an object containing a return value, that is later catch
ed by a function made by $label
.
That means, you can't use try .. catch .. finally
blocks normally in any code that utilizes reto-js
. Since exceptions used to pass the values to outer labeled functions mustn't be catched by your code, you need to use $rethrow
function provided by the library in the very beginning of every catch
block where unwanted exception can appear. $rethrow
just rethrows given exception if it was generated by $return
and does nothing otherwise.
Example usage:
var r = $label('foo', () => {
try {
$return('foo', 'some-value');
} catch (e) {
$rethrow(e);
return 'another-value';
}
});
The above example outputs 'some-value'
as expected.
Functions
$label
Used to mark the given function with label. Order of the arguments is completely ignored. string
argument defines the label value and bool
argument determines if the wrapped function will be returned (true
) or will it be called immediately (false
, default behavior).
$return
If called with two arguments, the first argument may be:
- a label, to which the value will be returned.
- a natural number, defining how many nested levels of labeled functions the value will be returned from.
If called with one argument, the value will be returned one level up.
$rethrow
Rethrows given exception if it was generated by $return
and does nothing otherwise.
License
MIT