redux-saga:呼叫与分叉并加入

redux-saga: call vs fork and join

在 redux-saga 中,出于什么原因您更喜欢使用 callforkjoin

例如,当调用 HTTP API 时,这样做的优缺点是什么:

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

与此相对:

const task = yield fork(apiWrapperFunction, arg1, arg2)
const result = yield join(task)

据我所知没有那么多,但是您可以取消 forkjoin 之间的任务。

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

当您改用 spawn 时,差异会更大。它将创建一个 detached fork,当父任务被取消时(例如)不会自动取消。

除了@Pier 的 ,

两者都可用于调用普通函数和生成器函数。

此外,fork(fn, ...args)fn 上执行 非阻塞 调用 - 而 call(fn, ...args) 是阻塞的。

示例:

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');
}

这里有一个有用的 fork。