ensuring v0.1.0
ensuring
JavaScript library emulating the with
keyword from Python.
Python's with
keyword uses the concept of context manager
to wrap a block of code within a context of execution (think of it like a function) that is always executed, no matter the outcome of the block (including an exception).
# Opening a file
with open('my-file') as file_pointer:
do_something_risky(file_pointer)
# Custom context manager
with my_context_manager():
do_something_risky()
In both scenarios, Python will execute an __enter__
and an __exit__
function before and after the block is evaluated, handling possible exceptions.
The ensuring
library offers a similar API.
EnsureSync
The EnsureSync
class is a base from which consumers can define their own context managers. Just inherit from the class and define your own enter
and exit
methods.
import { EnsureSync } from 'ensuring';
class Logger extends EnsureSync {
exit(error, result) {
if (error) {
console.error(`Got error: ${error}`);
}
console.log(`Got result: ${result}`);
return result;
}
}
Logger.ensure(myFunction);
Logger.ensure(context, myFunction);
EnsureSync.enter
The enter
method can be used to setup the environment in which the function will be called. Since the context is saved on class construction (if any), it can be accessed as this.context
.
EnsureSync.exit
The exit
method is passed error generated by the wrapped function (if any) and the return value of the wrapper function (if any). It returns the value that should be passed to the environment, so you can process the wrapped function outcome.
EnsureAsync
Just like EnsureSync
, but awaits for the wrapped function before executing exit
.
4 years ago