11

In redux-saga, for what reasons might you favor using call vs. fork and join?

For example, when calling an HTTP API, what are the pros and cons of doing this:

const result = yield call(apiWrapperFunction, arg1, arg2)

versus this:

const task = yield fork(apiWrapperFunction, arg1, arg2)
const result = yield join(task)
James Nail
  • 1,481
  • 14
  • 22

2 Answers2

11

Not that much as far as I can tell, but you can then cancel the task between the fork and the join.

const task = yield fork(api, arg);

if (someCondition) {
  yield cancel(task);
}

const result = yield join(task);

// Now a no-op since `join` blocked for the task to finish
cancel(task);

The difference is way bigger when you use spawn instead. It will create a detached fork that is not automatically canceled when the parent task is (for example).

Pier Paolo Ramon
  • 2,255
  • 19
  • 22
11

In addition to @Pier's answer,

Both can be used to invoke normal and generator functions.

Also, fork(fn, ...args) perform a non-blocking call on fn - while call(fn, ...args) is blocking.

Example:

function* main() {
    yield fork(someSaga);
    console.log('this won't wait for the completion of someSaga');
}

function* main() {
    yield call(someSaga);
    console.log('this will wait for the completion of someSaga');
}

Here a useful example of fork.

Idan Dagan
  • 6,637
  • 3
  • 26
  • 37
  • `this will wait for the completion of someSaga` - Does this mean, I can think of saga's as a pipeline of saga's being executed one after the other if `call` is being used? If so, its handled within redux saga library? – Nevin Madhukar K Apr 26 '21 at 07:11
  • @NevinMadhukarK that's pretty accurate. – Slbox May 14 '21 at 23:53