7

I'm using a Redux Saga template and it uses generator functions that contain instances of yield call(). Basically it looks like this:

function *a(){
  yield call(<some function>);
}

yield takeLatest(SOME_ACTION, a)

My questions are as follows:

1) Am I correct that the reason for using

function *a(){
  yield call(<some function>());
}

instead of

function a(){
  <some function>()
}

is that with the first one, the generator function will wait until the yield call line has returned before proceeding, whereas in the second one, () will be called asynchronously?

2) If I'm correct about (1) ^^, then calling some_function inside a seems the same as the following:

async a() {
  await some_function();
}

Is this correct?

3) If I'm correct about (2) ^^, then it seems like the only reason to use generator functions instead of async/await is that generator functions can be called from yield takeLatest etc. Is this correct? Or is there some other rational behind it?

Thanks!

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

1

'yield' will wait until generator is unrolled to this 'yield' iteration.

The idea of saga generator (worker) is to generate special functions (so called 'effects') using effect creators (put, call etc), not just do something. This allows to orchestrate function calls.

See also Redux Saga async/await pattern

SalientBrain
  • 2,431
  • 16
  • 18
-1

Generator functions are more flexible and can be used for yielding different things depending on the number of times it gets used. Pagination of some sort comes to my mind. Here are some examples of generator functions that would be trickier to implement using async/await:

https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch4.md#multiple-iterators

mattemyo
  • 99
  • 1
  • 4