Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-saga: call vs fork and join

Tags:

redux-saga

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)
like image 353
James Nail Avatar asked Dec 13 '17 17:12

James Nail


2 Answers

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.

like image 67
Idan Dagan Avatar answered Nov 18 '22 00:11

Idan Dagan


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).

like image 20
Pier Paolo Ramon Avatar answered Nov 17 '22 22:11

Pier Paolo Ramon