Basic Generator Function for Asynchronous Flows
Demonstrate the creation of a simple generator function to manage asynchronous flows, yielding promises and managing their resolution within a Redux-Saga context.
function* fetchUserData() {
// Using yield to wait for the promise to resolve
const user = yield fetch('https://api.example.com/user').then(res => res.json());
return user;
}
This generator function fetchUserData uses yield to pause execution until the fetch promise resolves, effectively managing an asynchronous flow.
function* mainSaga() {
// Wait for a specific action to dispatch
yield take('FETCH_USER_REQUEST');
// Call fetchUserData and wait for it to finish
const userData = yield call(fetchUserData);
// Dispatch an action with the result of the fetch
yield put({ type: 'FETCH_USER_SUCCESS', payload: userData });
}
mainSaga waits for a 'FETCH_USER_REQUEST' action, then processes the asynchronous fetchUserData generator function, and finally dispatches the success action with the fetched data.