@gxyz/util.func v0.1.1
@gxyz/util.func
@gxyz/util.func is a lightweight utility library for easy use of (returns) functions.
Installation
Install the module locally via your favorite npm client, like npm:
npm install @gxyz/util.func
or yarn:
yarn add @gxyz/util.func
Usage
const {compose, tryCatch,} = require('@gxyz/util.func');
compose(…functions)
Compose async funcs. Take a look at the MDN Web Docs - Using Promises - Composition.
Compose takes an arguments object of async funcs or promises or an array of async funcs or promises.
Compose returns a function, arguments object passed to this function will be used as arguments object of the first element of …functions
.
Compose returned func returns an object as promise:
- If all
…functions
are fulfilled, returned obj will have avalue
prop with the reduced value. - If any of
…functions
is rejected, returned obj will have areason
prop with err.
async function dealAsyncFuncs(...args) {
const {reason, value,} = await compose(func0, func1, func2)(...args);
if (reason instanceof Error) {
throw reason;
}
return value;
}
tryCatch(func)
Better manage errors within async funcs.
tryCatch takes an async func or a promise as arg.
tryCatch returns a function, arguments object passed to this function will be used as argument object to func
.
tryCatch returned func returns an object as promise:
- If
func
is fulfilled, returned obj will have avalue
prop with returned value. - If
func
is rejected, returned obj will have areason
prop with err.
async function dealAsyncFunc(...args) {
const {reason, value,} = await tryCatch(func)(...args);
if (reason instanceof Error) {
throw reason;
}
return value;
}
Credits
Aziz Da |