Banica
Handle async processes like a boss. Implementation of the command pattern using generators. Or in other words a redux-saga but without the Redux bit.
- Read the story of the library
- CodePen to play with codepen.io/krasimir/pen/YEvNqx
Installation
yarn add banica
or npm install banica -S
. The library is available also as a single JavaScript file here.
Usage
The library exports just two merhods call
and run
. call
is used to wrap your function calls so the run
function recognizes them as commands. That run
function accepts a generator function or a created generator. For example:
; const isItTimeForBreakfast = true;const getFood = { ;};const eat = `I'll take for breakfast!`; const goodMorning = { const ready = ; if ready const food = ; const message = ; console; // I'll take banica for breakfast } ;
Error handling
Just wrap the yield
statements into a try-catch block. An error is send back to your generator in the following cases:
- Your function throws an error
- Your function returns a promise that gets rejected
const broken = { throw 'Ops, it is broken!';}const brokenAPI = { return { ; };} const program = { try ; catch error ... // "Ops, it is broken!" error try ; catch error ... // "Ops, the API is broken!" error}
API
call(<func or generator function>, ...args)
call
function accepts a function or generator function and arguments that need to be passed down. For example:
const formatMessage = `Hello `;//...later in a generator ; orconst getGreeting = 'Hello';const formatMessage = { const greeting = ; return ` `;}//...later in a generator ;
What you can yield call
is:
- A function
- A function that returns a promise
- A generator function
The call
method returns an object of the form
type: 'call' func: <your
run(<generator or generator function>)
Either create your generator upfront or send the generator function.
{ // ...} ;// or;
The run
method returns a promise that gets resolved when your generator is completed:
;