I do not understand what the mechanism of the call method is and that it should naturally yield a promise, but instead return the resolved value of that promise.
line 14👇:
import { put, call, takeLatest } from "redux-saga/effects";
import * as api from "./api";
//generate watchers
function* rootSaga() {
//define watcher
yield takeLatest("FETCH_TASKS_STARTED", fetchTasks);
}
//watcher is subProgram.They are executed when an particular action of the dispatched
function* fetchTasks() {
try {
yield put({
type: "REQUEST_STARTED",
});
const { data } = yield call(api.fetchTasks);
yield put({
type: "FETCH_TASKS_SUCCEED",
payLoad: { tasks: data },
});
} catch (e) {
yield put({
type: "REQUEST_FAILED",
payLoad: { error: e.message },
});
}
}
export default rootSaga;
The source code for the call effect can be found here
The call effect starts by calling whatever you asked it to call, then it checks what was returned. If you return a promise (eg, if you use call
with an async function), it waits for that promise to resolve, via a helper function called resolvePromise
. resolvePromise basically just calls .then
on the promise, passing in a callback. The callback is the function that knows how to resume the saga, which it will do by calling .next()
.
If you return an iterator (eg, if you use call
with a saga), it hands control over to the proc
function, which is the function responsible for running sagas. That code also checks for promises and waits for them to resolve, on this line