@gxyz/util.func
v0.1.1
Published
@gxyz/util.func is a lightweight utility library for easy use of (returns) functions
Maintainers
Readme
@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.funcor yarn:
yarn add @gxyz/util.funcUsage
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
…functionsare fulfilled, returned obj will have avalueprop with the reduced value. - If any of
…functionsis rejected, returned obj will have areasonprop 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
funcis fulfilled, returned obj will have avalueprop with returned value. - If
funcis rejected, returned obj will have areasonprop with err.
async function dealAsyncFunc(...args) {
const {reason, value,} = await tryCatch(func)(...args);
if (reason instanceof Error) {
throw reason;
}
return value;
}Credits
|
|
|:---:|
| Aziz Da |
