Generator function and Redux saga
With ES6, we have been introduced with a special type of functions called generators. With generators, the functions can be paused in the middle multiple times and resumed later which allows other codes to run in between.
Inside the generator function, we use a special keyword called yield which is used to pause the function inside itself.
So, a generator function can be stopped and restarted as many times as we like.With normal functions, we get parameters in the beginning and a return statement in the end. With generator functions, you send messages out with each yield
, and you send messages back in with each restart.
The syntax of generator function is like this —
function* abc()// code here}
Generator functions are like normal javascript functions only. The only thing to play with inside it is yield keyword.
yield takes an expression which is send to the generator and whatever is send inside is the computed result of that yield expression.
In Redux saga, yield is a built in function which allows to use generator functions sequentially. When used in Javascript, the generator functions will allow to yield all values from the nested functions.
function* one(){}function* abc(){const result = yield* one();}
Redux saga provides helper functions for performing asynchronous actions.
For example, the above code can be written like this
function* one(){}function* abc(){const result = yield call one();}
It allows you to wrap internal functions and dispatch specific actions to the store.
To read more about helper functions, click here.
Have any questions? Leave a comment.