redux-saga: call vs fork and join
Asked Answered
A

2

16

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)
Attribute answered 13/12, 2017 at 17:21 Comment(0)
N
14

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

Nacreous answered 13/12, 2017 at 20:10 Comment(0)
C
20

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.

Catching answered 4/2, 2019 at 11:59 Comment(2)
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?Hiedihiemal
@NevinMadhukarK that's pretty accurate.Osmunda
N
14

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

Nacreous answered 13/12, 2017 at 20:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.