Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/klntsky/reto-js
Return from outer functions
https://github.com/klntsky/reto-js
Last synced: 19 days ago
JSON representation
Return from outer functions
- Host: GitHub
- URL: https://github.com/klntsky/reto-js
- Owner: klntsky
- Created: 2017-02-20T09:56:31.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2022-12-30T20:47:44.000Z (about 2 years ago)
- Last Synced: 2024-10-28T17:03:35.105Z (2 months ago)
- Language: JavaScript
- Size: 304 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 9
-
Metadata Files:
- Readme: README.html
Awesome Lists containing this project
README
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.
})();off 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 the return value, that is latercatch
ed by a function made by$label
.That means, you can't use
try .. catch .. finally
blocks normally in any code that utilizesreto.js
. Since exceptions used to pass 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 everycatch
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 given function with label. Order of the arguments is completely ignored.
string
argument defines label value andbool
argument determines if the wrapped function will be returned (true
) or will it be called immedeately (false
, default behavior).$return
If called with two arguments, the first argument may be:
- a label, to which the value need to be returned.
- a natural number, defining how many nested levels of labeled functions you need to return from.
If called with one argument, value will be returned one level up.
$rethrow
Rethrows given exception if it was generated by $return
and does nothing otherwise.