# 3.4 Redux-Saga

原 Redux 流程為先對 Component 做 `connect` ，之後便可使用 Store 的 `dispatch` 觸發預先在 Reducer 中寫好的邏輯。\
而 Redux - Saga 的流程同樣是先對 Component 做 `connect` ，但 `dispatch` 觸發的事件為 React - Saga 預先訂閱的名稱，在該事件裡才依照流程去觸發需執行的 Reducer 邏輯。

**原本被 `dispatch` 觸發的 Method 從 Reducer 變成 Redux - Saga 。**

function ＊ --> Generator Function\
**Generator Function 能夠配合 `yield` 在執行的過程中喊停。**

yield&#x20;

* **call** 執行function     yield call(function, arg1, arg2)
* **put** 觸發dispatch

### Call vs Fork

saga 中 call 和 fork 都是用來執行指定函数 fn，區別在於：

* call effect 會阻塞當前 saga 的執行，直到被調用函数 fn 返回结果，才會執行下一步代碼。
* fork effect 則不會阻塞當前 saga，會立即返回一個 task 對象。

```
function fn() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('hello saga');
    }, 2000);
  });
}

function* fetchData() {
  // 等待 2 秒後，印出歡迎詞（阻塞）
  const greeting = yield call(fn);
  console.log('greeting: ', greeting);

  // 立即打印 task 對象（非阻塞）
  const task = yield fork(fn);
  console.log('task: ', task);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack1in.gitbook.io/font-end/3.-react/3.4-redux-saga.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
