[문서화] Dispatch 비동기 처리 순서 보장 솔루션 문서 작성
dispatch 비동기 처리 순서 보장 문제와 해결 방법을 체계적으로 정리한 문서를 작성했습니다. ## 작성된 문서 1. README.md - 전체 개요 및 목차 2. 01-problem.md - 문제 상황 및 원인 분석 3. 02-solution-dispatch-helper.md - dispatchHelper.js 솔루션 4. 03-solution-async-utils.md - asyncActionUtils.js 솔루션 5. 04-solution-queue-system.md - 큐 기반 패널 액션 시스템 6. 05-usage-patterns.md - 사용 패턴 및 실전 예제 ## 주요 내용 ### 문제 - Redux-thunk에서 여러 dispatch 순서가 보장되지 않는 문제 - setTimeout(fn, 0) 임시방편의 한계 ### 해결 방법 1. **dispatchHelper.js** (2025-11-05) - createSequentialDispatch: Promise 체인 기반 순차 실행 - createApiThunkWithChain: API 후 dispatch 체이닝 - withLoadingState: 로딩 상태 자동 관리 2. **asyncActionUtils.js** (2025-11-06) - 성공 기준 명확화: HTTP 200-299 + retCode 0/'0' - reject 없이 resolve만 사용하여 Promise 체인 보장 - 타임아웃 지원 3. **큐 기반 패널 액션 시스템** (2025-11-06) - queuedPanelActions.js: 패널 액션 큐 - panelQueueMiddleware.js: 자동 큐 처리 - 비동기 액션 순차 실행 ## 관련 커밋 -9490d72[251105] feat: dispatchHelper.js -5bd2774[251106] feat: Queued Panel functions -f9290a1[251106] fix: Dispatch Queue implementation
This commit is contained in:
210
.docs/dispatch-async/01-problem.md
Normal file
210
.docs/dispatch-async/01-problem.md
Normal file
@@ -0,0 +1,210 @@
|
||||
# 문제 상황: Dispatch 비동기 순서 미보장
|
||||
|
||||
## 🔴 핵심 문제
|
||||
|
||||
Redux-thunk는 비동기 액션을 지원하지만, **여러 개의 dispatch를 순차적으로 호출할 때 실행 순서가 보장되지 않습니다.**
|
||||
|
||||
## 📝 기존 코드의 문제점
|
||||
|
||||
### 예제 1: homeActions.js
|
||||
|
||||
**파일**: `src/actions/homeActions.js`
|
||||
|
||||
```javascript
|
||||
export const getHomeTerms = (props) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
if (response.data.retCode === 0) {
|
||||
// 첫 번째 dispatch
|
||||
dispatch({
|
||||
type: types.GET_HOME_TERMS,
|
||||
payload: response.data,
|
||||
});
|
||||
|
||||
// 두 번째 dispatch
|
||||
dispatch({
|
||||
type: types.SET_TERMS_ID_MAP,
|
||||
payload: termsIdMap,
|
||||
});
|
||||
|
||||
// ⚠️ 문제: setTimeout으로 순서 보장 시도
|
||||
setTimeout(() => {
|
||||
dispatch(getTermsAgreeYn());
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, "get", URLS.GET_HOME_TERMS, ..., onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
**문제점**:
|
||||
1. `setTimeout(fn, 0)`은 임시방편일 뿐, 명확한 해결책이 아님
|
||||
2. 코드 가독성이 떨어짐
|
||||
3. 타이밍 이슈로 인한 버그 가능성
|
||||
4. 유지보수가 어려움
|
||||
|
||||
### 예제 2: cartActions.js
|
||||
|
||||
**파일**: `src/actions/cartActions.js`
|
||||
|
||||
```javascript
|
||||
export const addToCart = (props) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
// 첫 번째 dispatch: 카트에 추가
|
||||
dispatch({
|
||||
type: types.ADD_TO_CART,
|
||||
payload: response.data.data,
|
||||
});
|
||||
|
||||
// 두 번째 dispatch: 카트 정보 재조회
|
||||
// ⚠️ 문제: 순서가 보장되지 않음
|
||||
dispatch(getMyInfoCartSearch({ mbrNo }));
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, "post", URLS.ADD_TO_CART, ..., onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
**문제점**:
|
||||
1. `getMyInfoCartSearch`가 `ADD_TO_CART`보다 먼저 실행될 수 있음
|
||||
2. 카트 정보가 업데이트되기 전에 재조회가 실행될 수 있음
|
||||
3. 순서가 보장되지 않아 UI에 잘못된 데이터가 표시될 수 있음
|
||||
|
||||
## 🤔 왜 순서가 보장되지 않을까?
|
||||
|
||||
### Redux-thunk의 동작 방식
|
||||
|
||||
```javascript
|
||||
// Redux-thunk는 이렇게 동작합니다
|
||||
function dispatch(action) {
|
||||
if (typeof action === 'function') {
|
||||
// thunk action인 경우
|
||||
return action(dispatch, getState);
|
||||
} else {
|
||||
// plain action인 경우
|
||||
return next(action);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 문제 시나리오
|
||||
|
||||
```javascript
|
||||
// 이렇게 작성하면
|
||||
dispatch({ type: 'ACTION_1' }); // Plain action - 즉시 실행
|
||||
dispatch(asyncAction()); // Thunk - 비동기 실행
|
||||
dispatch({ type: 'ACTION_2' }); // Plain action - 즉시 실행
|
||||
|
||||
// 실제 실행 순서는
|
||||
// 1. ACTION_1 (동기)
|
||||
// 2. ACTION_2 (동기)
|
||||
// 3. asyncAction의 내부 dispatch들 (비동기)
|
||||
|
||||
// 즉, asyncAction이 완료되기 전에 ACTION_2가 실행됩니다!
|
||||
```
|
||||
|
||||
## 🎯 해결해야 할 과제
|
||||
|
||||
1. **순서 보장**: 여러 dispatch가 의도한 순서대로 실행되도록
|
||||
2. **에러 처리**: 중간에 에러가 발생해도 체인이 끊기지 않도록
|
||||
3. **가독성**: 코드가 직관적이고 유지보수하기 쉽도록
|
||||
4. **재사용성**: 여러 곳에서 쉽게 사용할 수 있도록
|
||||
5. **호환성**: 기존 코드와 호환되도록
|
||||
|
||||
## 📊 실제 발생 가능한 버그
|
||||
|
||||
### 시나리오 1: 카트 추가 후 조회
|
||||
|
||||
```javascript
|
||||
// 의도한 순서
|
||||
1. ADD_TO_CART dispatch
|
||||
2. 상태 업데이트
|
||||
3. getMyInfoCartSearch dispatch
|
||||
4. 최신 카트 정보 조회
|
||||
|
||||
// 실제 실행 순서 (문제)
|
||||
1. ADD_TO_CART dispatch
|
||||
2. getMyInfoCartSearch dispatch (너무 빨리 실행!)
|
||||
3. 이전 카트 정보 조회 (아직 상태 업데이트 안됨)
|
||||
4. 상태 업데이트
|
||||
→ 결과: UI에 이전 데이터가 표시됨
|
||||
```
|
||||
|
||||
### 시나리오 2: 패널 열고 닫기
|
||||
|
||||
```javascript
|
||||
// 의도한 순서
|
||||
1. PUSH_PANEL (검색 패널 열기)
|
||||
2. UPDATE_PANEL (검색 결과 표시)
|
||||
3. POP_PANEL (이전 패널 닫기)
|
||||
|
||||
// 실제 실행 순서 (문제)
|
||||
1. PUSH_PANEL
|
||||
2. POP_PANEL (너무 빨리 실행!)
|
||||
3. UPDATE_PANEL (이미 닫힌 패널을 업데이트)
|
||||
→ 결과: 패널이 제대로 표시되지 않음
|
||||
```
|
||||
|
||||
## 🔧 기존 해결 방법과 한계
|
||||
|
||||
### 방법 1: setTimeout 사용
|
||||
|
||||
```javascript
|
||||
dispatch(action1());
|
||||
setTimeout(() => {
|
||||
dispatch(action2());
|
||||
}, 0);
|
||||
```
|
||||
|
||||
**한계**:
|
||||
- 명확한 순서 보장 없음
|
||||
- 타이밍에 의존적
|
||||
- 코드 가독성 저하
|
||||
- 유지보수 어려움
|
||||
|
||||
### 방법 2: 콜백 중첩
|
||||
|
||||
```javascript
|
||||
const action1 = (callback) => (dispatch, getState) => {
|
||||
dispatch({ type: 'ACTION_1' });
|
||||
if (callback) callback();
|
||||
};
|
||||
|
||||
dispatch(action1(() => {
|
||||
dispatch(action2(() => {
|
||||
dispatch(action3());
|
||||
}));
|
||||
}));
|
||||
```
|
||||
|
||||
**한계**:
|
||||
- 콜백 지옥
|
||||
- 에러 처리 복잡
|
||||
- 코드 가독성 최악
|
||||
|
||||
### 방법 3: async/await
|
||||
|
||||
```javascript
|
||||
export const complexAction = () => async (dispatch, getState) => {
|
||||
await dispatch(action1());
|
||||
await dispatch(action2());
|
||||
await dispatch(action3());
|
||||
};
|
||||
```
|
||||
|
||||
**한계**:
|
||||
- Chrome 68 호환성 문제 (프로젝트 요구사항)
|
||||
- 모든 action이 Promise를 반환해야 함
|
||||
- 기존 코드 대량 수정 필요
|
||||
|
||||
## 🎯 다음 단계
|
||||
|
||||
이제 이러한 문제들을 해결하기 위한 3가지 솔루션을 살펴보겠습니다:
|
||||
|
||||
1. [dispatchHelper.js](./02-solution-dispatch-helper.md) - Promise 체인 기반 헬퍼 함수
|
||||
2. [asyncActionUtils.js](./03-solution-async-utils.md) - Promise 기반 비동기 처리 유틸리티
|
||||
3. [큐 기반 패널 액션 시스템](./04-solution-queue-system.md) - 미들웨어 기반 큐 시스템
|
||||
|
||||
---
|
||||
|
||||
**다음**: [해결 방법 1: dispatchHelper.js →](./02-solution-dispatch-helper.md)
|
||||
541
.docs/dispatch-async/02-solution-dispatch-helper.md
Normal file
541
.docs/dispatch-async/02-solution-dispatch-helper.md
Normal file
@@ -0,0 +1,541 @@
|
||||
# 해결 방법 1: dispatchHelper.js
|
||||
|
||||
## 📦 개요
|
||||
|
||||
**파일**: `src/utils/dispatchHelper.js`
|
||||
**작성일**: 2025-11-05
|
||||
**커밋**: `9490d72 [251105] feat: dispatchHelper.js`
|
||||
|
||||
Promise 체인 기반의 dispatch 순차 실행 헬퍼 함수 모음입니다.
|
||||
|
||||
## 🎯 핵심 함수
|
||||
|
||||
1. `createSequentialDispatch` - 순차적 dispatch 실행
|
||||
2. `createApiThunkWithChain` - API 후 dispatch 자동 체이닝
|
||||
3. `withLoadingState` - 로딩 상태 자동 관리
|
||||
4. `createConditionalDispatch` - 조건부 dispatch
|
||||
5. `createParallelDispatch` - 병렬 dispatch
|
||||
|
||||
---
|
||||
|
||||
## 1️⃣ createSequentialDispatch
|
||||
|
||||
### 설명
|
||||
|
||||
여러 dispatch를 **Promise 체인**을 사용하여 순차적으로 실행합니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```javascript
|
||||
import { createSequentialDispatch } from '../utils/dispatchHelper';
|
||||
|
||||
// 기본 사용
|
||||
dispatch(createSequentialDispatch([
|
||||
{ type: types.SET_LOADING, payload: true },
|
||||
{ type: types.UPDATE_DATA, payload: data },
|
||||
{ type: types.SET_LOADING, payload: false }
|
||||
]));
|
||||
|
||||
// thunk와 plain action 혼합
|
||||
dispatch(createSequentialDispatch([
|
||||
{ type: types.GET_HOME_TERMS, payload: response.data },
|
||||
{ type: types.SET_TERMS_ID_MAP, payload: termsIdMap },
|
||||
getTermsAgreeYn() // thunk action
|
||||
]));
|
||||
|
||||
// 옵션 사용
|
||||
dispatch(createSequentialDispatch([
|
||||
fetchUserData(),
|
||||
fetchCartData(),
|
||||
fetchOrderData()
|
||||
], {
|
||||
delay: 100, // 각 dispatch 간 100ms 지연
|
||||
stopOnError: true // 에러 발생 시 중단
|
||||
}));
|
||||
```
|
||||
|
||||
### Before & After
|
||||
|
||||
#### Before (setTimeout 방식)
|
||||
|
||||
```javascript
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.GET_HOME_TERMS, payload: response.data });
|
||||
dispatch({ type: types.SET_TERMS_ID_MAP, payload: termsIdMap });
|
||||
setTimeout(() => { dispatch(getTermsAgreeYn()); }, 0);
|
||||
};
|
||||
```
|
||||
|
||||
#### After (createSequentialDispatch)
|
||||
|
||||
```javascript
|
||||
const onSuccess = (response) => {
|
||||
dispatch(createSequentialDispatch([
|
||||
{ type: types.GET_HOME_TERMS, payload: response.data },
|
||||
{ type: types.SET_TERMS_ID_MAP, payload: termsIdMap },
|
||||
getTermsAgreeYn()
|
||||
]));
|
||||
};
|
||||
```
|
||||
|
||||
### 구현 원리
|
||||
|
||||
**파일**: `src/utils/dispatchHelper.js:96-129`
|
||||
|
||||
```javascript
|
||||
export const createSequentialDispatch = (dispatchActions, options) =>
|
||||
(dispatch, getState) => {
|
||||
const config = options || {};
|
||||
const delay = config.delay || 0;
|
||||
const stopOnError = config.stopOnError !== undefined ? config.stopOnError : false;
|
||||
|
||||
// Promise 체인으로 순차 실행
|
||||
return dispatchActions.reduce(
|
||||
(promise, action, index) => {
|
||||
return promise
|
||||
.then(() => {
|
||||
// delay가 설정되어 있고 첫 번째가 아닌 경우 지연
|
||||
if (delay > 0 && index > 0) {
|
||||
return new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
return Promise.resolve();
|
||||
})
|
||||
.then(() => {
|
||||
// action 실행
|
||||
const result = dispatch(action);
|
||||
|
||||
// Promise인 경우 대기
|
||||
if (result && typeof result.then === 'function') {
|
||||
return result;
|
||||
}
|
||||
return Promise.resolve(result);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('createSequentialDispatch error at index', index, error);
|
||||
|
||||
// stopOnError가 true면 에러를 다시 throw
|
||||
if (stopOnError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// stopOnError가 false면 계속 진행
|
||||
return Promise.resolve();
|
||||
});
|
||||
},
|
||||
Promise.resolve()
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
**핵심 포인트**:
|
||||
1. `Array.reduce()`로 Promise 체인 구성
|
||||
2. 각 action이 완료되면 다음 action 실행
|
||||
3. thunk가 Promise를 반환하면 대기
|
||||
4. 에러 처리 옵션 지원
|
||||
|
||||
---
|
||||
|
||||
## 2️⃣ createApiThunkWithChain
|
||||
|
||||
### 설명
|
||||
|
||||
API 호출 후 성공 콜백에서 여러 dispatch를 자동으로 체이닝합니다.
|
||||
TAxios의 onSuccess/onFail 패턴과 완벽하게 호환됩니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```javascript
|
||||
import { createApiThunkWithChain } from '../utils/dispatchHelper';
|
||||
|
||||
// 기본 사용
|
||||
export const addToCart = (props) =>
|
||||
createApiThunkWithChain(
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'post', URLS.ADD_TO_CART, {}, props, onSuccess, onFail);
|
||||
},
|
||||
[
|
||||
(response) => ({ type: types.ADD_TO_CART, payload: response.data.data }),
|
||||
(response) => getMyInfoCartSearch({ mbrNo: response.data.data.mbrNo })
|
||||
]
|
||||
);
|
||||
|
||||
// 에러 처리 포함
|
||||
export const registerDevice = (params) =>
|
||||
createApiThunkWithChain(
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'post', URLS.REGISTER_DEVICE, {}, params, onSuccess, onFail);
|
||||
},
|
||||
[
|
||||
(response) => ({ type: types.REGISTER_DEVICE, payload: response.data.data }),
|
||||
getAuthenticationCode(),
|
||||
fetchCurrentUserHomeTerms()
|
||||
],
|
||||
(error) => ({ type: types.API_ERROR, payload: error })
|
||||
);
|
||||
```
|
||||
|
||||
### Before & After
|
||||
|
||||
#### Before
|
||||
|
||||
```javascript
|
||||
export const addToCart = (props) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.ADD_TO_CART, payload: response.data.data });
|
||||
dispatch(getMyInfoCartSearch({ mbrNo }));
|
||||
};
|
||||
|
||||
const onFail = (error) => {
|
||||
console.error(error);
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, "post", URLS.ADD_TO_CART, {}, props, onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
#### After
|
||||
|
||||
```javascript
|
||||
export const addToCart = (props) =>
|
||||
createApiThunkWithChain(
|
||||
(d, gs, onS, onF) => TAxios(d, gs, 'post', URLS.ADD_TO_CART, {}, props, onS, onF),
|
||||
[
|
||||
(response) => ({ type: types.ADD_TO_CART, payload: response.data.data }),
|
||||
(response) => getMyInfoCartSearch({ mbrNo: response.data.data.mbrNo })
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
### 구현 원리
|
||||
|
||||
**파일**: `src/utils/dispatchHelper.js:170-211`
|
||||
|
||||
```javascript
|
||||
export const createApiThunkWithChain = (
|
||||
apiCallFactory,
|
||||
successDispatchActions,
|
||||
errorDispatch
|
||||
) => (dispatch, getState) => {
|
||||
const actions = successDispatchActions || [];
|
||||
|
||||
const enhancedOnSuccess = (response) => {
|
||||
// 성공 시 순차적으로 dispatch 실행
|
||||
actions.forEach((action, index) => {
|
||||
setTimeout(() => {
|
||||
if (typeof action === 'function') {
|
||||
// action이 함수인 경우 (동적 action creator)
|
||||
// response를 인자로 전달하여 실행
|
||||
const dispatchAction = action(response);
|
||||
dispatch(dispatchAction);
|
||||
} else {
|
||||
// action이 객체인 경우 (plain action)
|
||||
dispatch(action);
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
};
|
||||
|
||||
const enhancedOnFail = (error) => {
|
||||
console.error('createApiThunkWithChain error:', error);
|
||||
|
||||
if (errorDispatch) {
|
||||
if (typeof errorDispatch === 'function') {
|
||||
const dispatchAction = errorDispatch(error);
|
||||
dispatch(dispatchAction);
|
||||
} else {
|
||||
dispatch(errorDispatch);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// API 호출 실행
|
||||
return apiCallFactory(dispatch, getState, enhancedOnSuccess, enhancedOnFail);
|
||||
};
|
||||
```
|
||||
|
||||
**핵심 포인트**:
|
||||
1. API 호출의 onSuccess/onFail 콜백을 래핑
|
||||
2. 성공 시 여러 action을 순차 실행
|
||||
3. response를 각 action에 전달 가능
|
||||
4. 에러 처리 action 지원
|
||||
|
||||
---
|
||||
|
||||
## 3️⃣ withLoadingState
|
||||
|
||||
### 설명
|
||||
|
||||
API 호출 thunk의 로딩 상태를 자동으로 관리합니다.
|
||||
`changeAppStatus`로 `showLoadingPanel`을 자동 on/off합니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```javascript
|
||||
import { withLoadingState } from '../utils/dispatchHelper';
|
||||
|
||||
// 기본 로딩 관리
|
||||
export const getProductDetail = (props) =>
|
||||
withLoadingState(
|
||||
(dispatch, getState) => {
|
||||
return TAxiosPromise(dispatch, getState, 'get', URLS.GET_PRODUCT_DETAIL, props, {})
|
||||
.then((response) => {
|
||||
dispatch({ type: types.GET_PRODUCT_DETAIL, payload: response.data.data });
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// 성공/에러 시 추가 dispatch
|
||||
export const fetchUserData = (userId) =>
|
||||
withLoadingState(
|
||||
fetchUser(userId),
|
||||
{
|
||||
loadingType: 'spinner',
|
||||
successDispatch: [
|
||||
fetchCart(userId),
|
||||
fetchOrders(userId)
|
||||
],
|
||||
errorDispatch: [
|
||||
(error) => ({ type: types.SHOW_ERROR_MESSAGE, payload: error.message })
|
||||
]
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Before & After
|
||||
|
||||
#### Before
|
||||
|
||||
```javascript
|
||||
export const getProductDetail = (props) => (dispatch, getState) => {
|
||||
// 로딩 시작
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: true } }));
|
||||
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.GET_PRODUCT_DETAIL, payload: response.data.data });
|
||||
// 로딩 종료
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
};
|
||||
|
||||
const onFail = (error) => {
|
||||
console.error(error);
|
||||
// 로딩 종료
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_PRODUCT_DETAIL, props, {}, onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
#### After
|
||||
|
||||
```javascript
|
||||
export const getProductDetail = (props) =>
|
||||
withLoadingState(
|
||||
(dispatch, getState) => {
|
||||
return TAxiosPromise(dispatch, getState, 'get', URLS.GET_PRODUCT_DETAIL, props, {})
|
||||
.then((response) => {
|
||||
dispatch({ type: types.GET_PRODUCT_DETAIL, payload: response.data.data });
|
||||
});
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### 구현 원리
|
||||
|
||||
**파일**: `src/utils/dispatchHelper.js:252-302`
|
||||
|
||||
```javascript
|
||||
export const withLoadingState = (thunk, options) => (dispatch, getState) => {
|
||||
const config = options || {};
|
||||
const loadingType = config.loadingType || 'wait';
|
||||
const successDispatch = config.successDispatch || [];
|
||||
const errorDispatch = config.errorDispatch || [];
|
||||
|
||||
// 로딩 시작
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: true, type: loadingType } }));
|
||||
|
||||
// thunk 실행
|
||||
const result = dispatch(thunk);
|
||||
|
||||
// Promise인 경우 처리
|
||||
if (result && typeof result.then === 'function') {
|
||||
return result
|
||||
.then((res) => {
|
||||
// 로딩 종료
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
|
||||
// 성공 시 추가 dispatch 실행
|
||||
successDispatch.forEach((action) => {
|
||||
if (typeof action === 'function') {
|
||||
dispatch(action(res));
|
||||
} else {
|
||||
dispatch(action);
|
||||
}
|
||||
});
|
||||
|
||||
return res;
|
||||
})
|
||||
.catch((error) => {
|
||||
// 로딩 종료
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
|
||||
// 에러 시 추가 dispatch 실행
|
||||
errorDispatch.forEach((action) => {
|
||||
if (typeof action === 'function') {
|
||||
dispatch(action(error));
|
||||
} else {
|
||||
dispatch(action);
|
||||
}
|
||||
});
|
||||
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
// 동기 실행인 경우
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
return result;
|
||||
};
|
||||
```
|
||||
|
||||
**핵심 포인트**:
|
||||
1. 로딩 시작/종료를 자동 관리
|
||||
2. Promise 기반 thunk만 지원
|
||||
3. 성공/실패 시 추가 action 실행 가능
|
||||
4. 에러 발생 시에도 로딩 상태 복원
|
||||
|
||||
---
|
||||
|
||||
## 4️⃣ createConditionalDispatch
|
||||
|
||||
### 설명
|
||||
|
||||
getState() 결과를 기반으로 조건에 따라 다른 dispatch를 실행합니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```javascript
|
||||
import { createConditionalDispatch } from '../utils/dispatchHelper';
|
||||
|
||||
// 단일 action 조건부 실행
|
||||
dispatch(createConditionalDispatch(
|
||||
(state) => state.common.appStatus.isAlarmEnabled === 'Y',
|
||||
addReservation(reservationData),
|
||||
deleteReservation(showId)
|
||||
));
|
||||
|
||||
// 여러 action 배열로 실행
|
||||
dispatch(createConditionalDispatch(
|
||||
(state) => state.common.appStatus.loginUserData.userNumber,
|
||||
[
|
||||
fetchUserProfile(),
|
||||
fetchUserCart(),
|
||||
fetchUserOrders()
|
||||
],
|
||||
[
|
||||
{ type: types.SHOW_LOGIN_REQUIRED_POPUP }
|
||||
]
|
||||
));
|
||||
|
||||
// false 조건 없이
|
||||
dispatch(createConditionalDispatch(
|
||||
(state) => state.cart.items.length > 0,
|
||||
proceedToCheckout()
|
||||
));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5️⃣ createParallelDispatch
|
||||
|
||||
### 설명
|
||||
|
||||
여러 API 호출을 병렬로 실행하고 모든 결과를 기다립니다.
|
||||
`Promise.all`을 사용합니다.
|
||||
|
||||
### 사용법
|
||||
|
||||
```javascript
|
||||
import { createParallelDispatch } from '../utils/dispatchHelper';
|
||||
|
||||
// 여러 API를 동시에 호출
|
||||
dispatch(createParallelDispatch([
|
||||
fetchUserProfile(),
|
||||
fetchUserCart(),
|
||||
fetchUserOrders()
|
||||
], { withLoading: true }));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 실제 사용 예제
|
||||
|
||||
### homeActions.js 개선
|
||||
|
||||
```javascript
|
||||
// Before
|
||||
export const getHomeTerms = (props) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
if (response.data.retCode === 0) {
|
||||
dispatch({ type: types.GET_HOME_TERMS, payload: response.data });
|
||||
dispatch({ type: types.SET_TERMS_ID_MAP, payload: termsIdMap });
|
||||
setTimeout(() => { dispatch(getTermsAgreeYn()); }, 0);
|
||||
}
|
||||
};
|
||||
TAxios(dispatch, getState, "get", URLS.GET_HOME_TERMS, ..., onSuccess, onFail);
|
||||
};
|
||||
|
||||
// After
|
||||
export const getHomeTerms = (props) =>
|
||||
createApiThunkWithChain(
|
||||
(d, gs, onS, onF) => TAxios(d, gs, "get", URLS.GET_HOME_TERMS, ..., onS, onF),
|
||||
[
|
||||
{ type: types.GET_HOME_TERMS, payload: response.data },
|
||||
{ type: types.SET_TERMS_ID_MAP, payload: termsIdMap },
|
||||
getTermsAgreeYn()
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
### cartActions.js 개선
|
||||
|
||||
```javascript
|
||||
// Before
|
||||
export const addToCart = (props) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.ADD_TO_CART, payload: response.data.data });
|
||||
dispatch(getMyInfoCartSearch({ mbrNo }));
|
||||
};
|
||||
TAxios(dispatch, getState, "post", URLS.ADD_TO_CART, ..., onSuccess, onFail);
|
||||
};
|
||||
|
||||
// After
|
||||
export const addToCart = (props) =>
|
||||
createApiThunkWithChain(
|
||||
(d, gs, onS, onF) => TAxios(d, gs, 'post', URLS.ADD_TO_CART, {}, props, onS, onF),
|
||||
[
|
||||
(response) => ({ type: types.ADD_TO_CART, payload: response.data.data }),
|
||||
(response) => getMyInfoCartSearch({ mbrNo: response.data.data.mbrNo })
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 장점
|
||||
|
||||
1. **간결성**: setTimeout 제거로 코드가 깔끔해짐
|
||||
2. **가독성**: 의도가 명확하게 드러남
|
||||
3. **재사용성**: 헬퍼 함수를 여러 곳에서 사용 가능
|
||||
4. **에러 처리**: 옵션으로 에러 처리 전략 선택 가능
|
||||
5. **호환성**: 기존 코드와 호환 (선택적 사용)
|
||||
|
||||
## ⚠️ 주의사항
|
||||
|
||||
1. **Promise 기반**: 모든 함수가 Promise를 반환하도록 설계됨
|
||||
2. **Chrome 68**: async/await 없이 Promise.then() 사용
|
||||
3. **기존 패턴**: TAxios의 onSuccess/onFail 패턴 유지
|
||||
|
||||
---
|
||||
|
||||
**다음**: [해결 방법 2: asyncActionUtils.js →](./03-solution-async-utils.md)
|
||||
711
.docs/dispatch-async/03-solution-async-utils.md
Normal file
711
.docs/dispatch-async/03-solution-async-utils.md
Normal file
@@ -0,0 +1,711 @@
|
||||
# 해결 방법 2: asyncActionUtils.js
|
||||
|
||||
## 📦 개요
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js`
|
||||
**작성일**: 2025-11-06
|
||||
**커밋**: `f9290a1 [251106] fix: Dispatch Queue implementation`
|
||||
|
||||
Promise 기반의 비동기 액션 처리와 **상세한 성공/실패 기준**을 제공합니다.
|
||||
|
||||
## 🎯 핵심 개념
|
||||
|
||||
### 프로젝트 특화 성공 기준
|
||||
|
||||
이 프로젝트에서 API 호출 성공은 **2가지 조건**을 모두 만족해야 합니다:
|
||||
|
||||
1. ✅ **HTTP 상태 코드**: 200-299 범위
|
||||
2. ✅ **retCode**: 0 또는 '0'
|
||||
|
||||
```javascript
|
||||
// HTTP 200이지만 retCode가 1인 경우
|
||||
{
|
||||
status: 200, // ✅ HTTP는 성공
|
||||
data: {
|
||||
retCode: 1, // ❌ retCode는 실패
|
||||
message: "권한이 없습니다"
|
||||
}
|
||||
}
|
||||
// → 이것은 실패입니다!
|
||||
```
|
||||
|
||||
### Promise 체인이 끊기지 않는 설계
|
||||
|
||||
**핵심 원칙**: 모든 비동기 작업은 **reject 없이 resolve만 사용**합니다.
|
||||
|
||||
```javascript
|
||||
// ❌ 일반적인 방식 (Promise 체인이 끊김)
|
||||
return new Promise((resolve, reject) => {
|
||||
if (error) {
|
||||
reject(error); // 체인이 끊김!
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ 이 프로젝트의 방식 (체인 유지)
|
||||
return new Promise((resolve) => {
|
||||
if (error) {
|
||||
resolve({
|
||||
success: false,
|
||||
error: { code: 'ERROR', message: '에러 발생' }
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 핵심 함수
|
||||
|
||||
1. `isApiSuccess` - API 성공 여부 판단
|
||||
2. `fetchApi` - Promise 기반 fetch 래퍼
|
||||
3. `tAxiosToPromise` - TAxios를 Promise로 변환
|
||||
4. `wrapAsyncAction` - 비동기 액션을 Promise로 래핑
|
||||
5. `withTimeout` - 타임아웃 지원
|
||||
6. `executeParallelAsyncActions` - 병렬 실행
|
||||
|
||||
---
|
||||
|
||||
## 1️⃣ isApiSuccess
|
||||
|
||||
### 설명
|
||||
|
||||
API 응답이 성공인지 판단하는 **프로젝트 표준 함수**입니다.
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:21-34`
|
||||
|
||||
```javascript
|
||||
export const isApiSuccess = (response, responseData) => {
|
||||
// 1️⃣ HTTP 상태 코드 확인 (200-299 성공 범위)
|
||||
if (!response.ok || response.status < 200 || response.status >= 300) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2️⃣ retCode 확인 - 0 또는 '0'이어야 성공
|
||||
if (responseData && responseData.retCode !== undefined) {
|
||||
return responseData.retCode === 0 || responseData.retCode === '0';
|
||||
}
|
||||
|
||||
// retCode가 없는 경우 HTTP 상태 코드만으로 판단
|
||||
return response.ok;
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
// 성공 케이스
|
||||
isApiSuccess(
|
||||
{ ok: true, status: 200 },
|
||||
{ retCode: 0, data: { ... } }
|
||||
); // → true
|
||||
|
||||
isApiSuccess(
|
||||
{ ok: true, status: 200 },
|
||||
{ retCode: '0', data: { ... } }
|
||||
); // → true
|
||||
|
||||
// 실패 케이스
|
||||
isApiSuccess(
|
||||
{ ok: true, status: 200 },
|
||||
{ retCode: 1, message: "권한 없음" }
|
||||
); // → false (retCode가 0이 아님)
|
||||
|
||||
isApiSuccess(
|
||||
{ ok: false, status: 500 },
|
||||
{ retCode: 0, data: { ... } }
|
||||
); // → false (HTTP 상태 코드가 500)
|
||||
|
||||
isApiSuccess(
|
||||
{ ok: false, status: 404 },
|
||||
{ retCode: 0 }
|
||||
); // → false (404 에러)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2️⃣ fetchApi
|
||||
|
||||
### 설명
|
||||
|
||||
**표준 fetch API를 Promise로 래핑**하여 프로젝트 성공 기준에 맞춰 처리합니다.
|
||||
|
||||
### 핵심 특징
|
||||
|
||||
- ✅ 항상 `resolve` 사용 (reject 없음)
|
||||
- ✅ HTTP 상태 + retCode 모두 확인
|
||||
- ✅ JSON 파싱 에러도 처리
|
||||
- ✅ 네트워크 에러도 처리
|
||||
- ✅ 상세한 로깅
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:57-123`
|
||||
|
||||
```javascript
|
||||
export const fetchApi = (url, options = {}) => {
|
||||
console.log('[asyncActionUtils] 🌐 FETCH_API_START', { url, method: options.method || 'GET' });
|
||||
|
||||
return new Promise((resolve) => { // ⚠️ 항상 resolve만 사용!
|
||||
fetch(url, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
},
|
||||
...options
|
||||
})
|
||||
.then(response => {
|
||||
// JSON 파싱
|
||||
return response.json()
|
||||
.then(responseData => {
|
||||
console.log('[asyncActionUtils] 📊 API_RESPONSE', {
|
||||
status: response.status,
|
||||
ok: response.ok,
|
||||
retCode: responseData.retCode,
|
||||
success: isApiSuccess(response, responseData)
|
||||
});
|
||||
|
||||
// ✅ 성공/실패 여부와 관계없이 항상 resolve
|
||||
resolve({
|
||||
response,
|
||||
data: responseData,
|
||||
success: isApiSuccess(response, responseData),
|
||||
error: !isApiSuccess(response, responseData) ? {
|
||||
code: responseData.retCode || response.status,
|
||||
message: responseData.message || getApiErrorMessage(responseData.retCode || response.status),
|
||||
httpStatus: response.status
|
||||
} : null
|
||||
});
|
||||
})
|
||||
.catch(parseError => {
|
||||
console.error('[asyncActionUtils] ❌ JSON_PARSE_ERROR', parseError);
|
||||
|
||||
// ✅ JSON 파싱 실패도 resolve로 처리
|
||||
resolve({
|
||||
response,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: 'PARSE_ERROR',
|
||||
message: '응답 데이터 파싱에 실패했습니다',
|
||||
originalError: parseError
|
||||
}
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('[asyncActionUtils] 💥 FETCH_ERROR', error);
|
||||
|
||||
// ✅ 네트워크 에러 등도 resolve로 처리
|
||||
resolve({
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: 'NETWORK_ERROR',
|
||||
message: error.message || '네트워크 오류가 발생했습니다',
|
||||
originalError: error
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
import { fetchApi } from '../utils/asyncActionUtils';
|
||||
|
||||
// 기본 사용
|
||||
const result = await fetchApi('/api/products/123', {
|
||||
method: 'GET'
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
console.log('성공:', result.data);
|
||||
// HTTP 200-299 + retCode 0/'0'
|
||||
} else {
|
||||
console.error('실패:', result.error);
|
||||
// error.code, error.message 사용 가능
|
||||
}
|
||||
|
||||
// POST 요청
|
||||
const result = await fetchApi('/api/cart', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ productId: 123 })
|
||||
});
|
||||
|
||||
// 헤더 추가
|
||||
const result = await fetchApi('/api/user', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': 'Bearer token123'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 반환 구조
|
||||
|
||||
```javascript
|
||||
// 성공 시
|
||||
{
|
||||
response: Response, // fetch Response 객체
|
||||
data: { ... }, // 파싱된 JSON 데이터
|
||||
success: true, // 성공 플래그
|
||||
error: null // 에러 없음
|
||||
}
|
||||
|
||||
// 실패 시 (HTTP 에러)
|
||||
{
|
||||
response: Response,
|
||||
data: { retCode: 1, message: "권한 없음" },
|
||||
success: false,
|
||||
error: {
|
||||
code: 1,
|
||||
message: "권한 없음",
|
||||
httpStatus: 200
|
||||
}
|
||||
}
|
||||
|
||||
// 실패 시 (네트워크 에러)
|
||||
{
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: 'NETWORK_ERROR',
|
||||
message: '네트워크 오류가 발생했습니다',
|
||||
originalError: Error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3️⃣ tAxiosToPromise
|
||||
|
||||
### 설명
|
||||
|
||||
프로젝트에서 사용하는 **TAxios를 Promise로 변환**합니다.
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:138-204`
|
||||
|
||||
```javascript
|
||||
export const tAxiosToPromise = (
|
||||
TAxios,
|
||||
dispatch,
|
||||
getState,
|
||||
method,
|
||||
baseUrl,
|
||||
urlParams,
|
||||
params,
|
||||
options = {}
|
||||
) => {
|
||||
return new Promise((resolve) => {
|
||||
console.log('[asyncActionUtils] 🔄 TAXIOS_TO_PROMISE_START', { method, baseUrl });
|
||||
|
||||
const enhancedOnSuccess = (response) => {
|
||||
console.log('[asyncActionUtils] ✅ TAXIOS_SUCCESS', { retCode: response?.data?.retCode });
|
||||
|
||||
// TAxios 성공 콜백도 성공 기준 적용
|
||||
const isSuccess = response?.data && (
|
||||
response.data.retCode === 0 ||
|
||||
response.data.retCode === '0'
|
||||
);
|
||||
|
||||
resolve({
|
||||
response,
|
||||
data: response.data,
|
||||
success: isSuccess,
|
||||
error: !isSuccess ? {
|
||||
code: response.data?.retCode || 'UNKNOWN_ERROR',
|
||||
message: response.data?.message || getApiErrorMessage(response.data?.retCode || 'UNKNOWN_ERROR')
|
||||
} : null
|
||||
});
|
||||
};
|
||||
|
||||
const enhancedOnFail = (error) => {
|
||||
console.error('[asyncActionUtils] ❌ TAXIOS_FAIL', error);
|
||||
|
||||
resolve({ // ⚠️ reject가 아닌 resolve
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: error.retCode || 'TAXIOS_ERROR',
|
||||
message: error.message || 'API 호출에 실패했습니다',
|
||||
originalError: error
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
method,
|
||||
baseUrl,
|
||||
urlParams,
|
||||
params,
|
||||
enhancedOnSuccess,
|
||||
enhancedOnFail,
|
||||
options.noTokenRefresh || false,
|
||||
options.responseType
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('[asyncActionUtils] 💥 TAXIOS_EXECUTION_ERROR', error);
|
||||
|
||||
resolve({
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: 'EXECUTION_ERROR',
|
||||
message: 'API 호출 실행 중 오류가 발생했습니다',
|
||||
originalError: error
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
import { tAxiosToPromise } from '../utils/asyncActionUtils';
|
||||
import { TAxios } from '../utils/TAxios';
|
||||
|
||||
export const getProductDetail = (productId) => async (dispatch, getState) => {
|
||||
const result = await tAxiosToPromise(
|
||||
TAxios,
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_PRODUCT_DETAIL,
|
||||
{},
|
||||
{ productId },
|
||||
{}
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
dispatch({
|
||||
type: types.GET_PRODUCT_DETAIL,
|
||||
payload: result.data.data
|
||||
});
|
||||
} else {
|
||||
console.error('상품 조회 실패:', result.error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4️⃣ wrapAsyncAction
|
||||
|
||||
### 설명
|
||||
|
||||
비동기 액션 함수를 Promise로 래핑하여 **표준화된 결과 구조**를 반환합니다.
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:215-270`
|
||||
|
||||
```javascript
|
||||
export const wrapAsyncAction = (asyncAction, context = {}) => {
|
||||
return new Promise((resolve) => {
|
||||
const { dispatch, getState } = context;
|
||||
|
||||
console.log('[asyncActionUtils] 🎯 WRAP_ASYNC_ACTION_START');
|
||||
|
||||
// 성공 콜백 - 항상 resolve 호출
|
||||
const onSuccess = (result) => {
|
||||
console.log('[asyncActionUtils] ✅ WRAP_ASYNC_SUCCESS', result);
|
||||
|
||||
resolve({
|
||||
response: result.response || result,
|
||||
data: result.data || result,
|
||||
success: true,
|
||||
error: null
|
||||
});
|
||||
};
|
||||
|
||||
// 실패 콜백 - 항상 resolve 호출 (reject 하지 않음)
|
||||
const onFail = (error) => {
|
||||
console.error('[asyncActionUtils] ❌ WRAP_ASYNC_FAIL', error);
|
||||
|
||||
resolve({
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: error.retCode || error.code || 'ASYNC_ACTION_ERROR',
|
||||
message: error.message || error.errorMessage || '비동기 작업에 실패했습니다',
|
||||
originalError: error
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
// 비동기 액션 실행
|
||||
const result = asyncAction(dispatch, getState, onSuccess, onFail);
|
||||
|
||||
// Promise를 반환하는 경우도 처리
|
||||
if (result && typeof result.then === 'function') {
|
||||
result
|
||||
.then(onSuccess)
|
||||
.catch(onFail);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[asyncActionUtils] 💥 WRAP_ASYNC_EXECUTION_ERROR', error);
|
||||
onFail(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
import { wrapAsyncAction } from '../utils/asyncActionUtils';
|
||||
|
||||
// 비동기 액션 정의
|
||||
const myAsyncAction = (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URL, {}, {}, onSuccess, onFail);
|
||||
};
|
||||
|
||||
// Promise로 래핑하여 사용
|
||||
const result = await wrapAsyncAction(myAsyncAction, { dispatch, getState });
|
||||
|
||||
if (result.success) {
|
||||
console.log('성공:', result.data);
|
||||
} else {
|
||||
console.error('실패:', result.error.message);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5️⃣ withTimeout
|
||||
|
||||
### 설명
|
||||
|
||||
Promise에 **타임아웃**을 적용합니다.
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:354-373`
|
||||
|
||||
```javascript
|
||||
export const withTimeout = (
|
||||
promise,
|
||||
timeoutMs,
|
||||
timeoutMessage = '작업 시간이 초과되었습니다'
|
||||
) => {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
console.error('[asyncActionUtils] ⏰ PROMISE_TIMEOUT', { timeoutMs });
|
||||
resolve({
|
||||
response: null,
|
||||
data: null,
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TIMEOUT',
|
||||
message: timeoutMessage,
|
||||
timeout: timeoutMs
|
||||
}
|
||||
});
|
||||
}, timeoutMs);
|
||||
})
|
||||
]);
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
import { withTimeout, fetchApi } from '../utils/asyncActionUtils';
|
||||
|
||||
// 5초 타임아웃
|
||||
const result = await withTimeout(
|
||||
fetchApi('/api/slow-endpoint'),
|
||||
5000,
|
||||
'요청이 시간초과 되었습니다'
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
console.log('성공:', result.data);
|
||||
} else if (result.error.code === 'TIMEOUT') {
|
||||
console.error('타임아웃 발생');
|
||||
} else {
|
||||
console.error('기타 에러:', result.error);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6️⃣ executeParallelAsyncActions
|
||||
|
||||
### 설명
|
||||
|
||||
여러 비동기 액션을 **병렬로 실행**하고 모든 결과를 기다립니다.
|
||||
|
||||
### 구현
|
||||
|
||||
**파일**: `src/utils/asyncActionUtils.js:279-299`
|
||||
|
||||
```javascript
|
||||
export const executeParallelAsyncActions = (asyncActions, context = {}) => {
|
||||
console.log('[asyncActionUtils] 🚀 EXECUTE_PARALLEL_START', { count: asyncActions.length });
|
||||
|
||||
const promises = asyncActions.map(action =>
|
||||
wrapAsyncAction(action, context)
|
||||
);
|
||||
|
||||
return Promise.all(promises)
|
||||
.then(results => {
|
||||
console.log('[asyncActionUtils] ✅ EXECUTE_PARALLEL_SUCCESS', {
|
||||
successCount: results.filter(r => r.success).length,
|
||||
failCount: results.filter(r => !r.success).length
|
||||
});
|
||||
return results;
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('[asyncActionUtils] ❌ EXECUTE_PARALLEL_ERROR', error);
|
||||
return [];
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 사용 예제
|
||||
|
||||
```javascript
|
||||
import { executeParallelAsyncActions } from '../utils/asyncActionUtils';
|
||||
|
||||
// 3개의 API를 동시에 호출
|
||||
const results = await executeParallelAsyncActions([
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URL1, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URL2, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URL3, {}, {}, onSuccess, onFail);
|
||||
}
|
||||
], { dispatch, getState });
|
||||
|
||||
// 결과 처리
|
||||
results.forEach((result, index) => {
|
||||
if (result.success) {
|
||||
console.log(`API ${index + 1} 성공:`, result.data);
|
||||
} else {
|
||||
console.error(`API ${index + 1} 실패:`, result.error);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 실제 사용 시나리오
|
||||
|
||||
### 시나리오 1: API 호출 후 후속 처리
|
||||
|
||||
```javascript
|
||||
import { tAxiosToPromise } from '../utils/asyncActionUtils';
|
||||
|
||||
export const addToCartAndRefresh = (productId) => async (dispatch, getState) => {
|
||||
// 1. 카트에 추가
|
||||
const addResult = await tAxiosToPromise(
|
||||
TAxios,
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.ADD_TO_CART,
|
||||
{},
|
||||
{ productId },
|
||||
{}
|
||||
);
|
||||
|
||||
if (addResult.success) {
|
||||
// 2. 카트 추가 성공 시 카트 정보 재조회
|
||||
dispatch({ type: types.ADD_TO_CART, payload: addResult.data.data });
|
||||
|
||||
const cartResult = await tAxiosToPromise(
|
||||
TAxios,
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_CART,
|
||||
{},
|
||||
{ mbrNo: addResult.data.data.mbrNo },
|
||||
{}
|
||||
);
|
||||
|
||||
if (cartResult.success) {
|
||||
dispatch({ type: types.GET_CART, payload: cartResult.data.data });
|
||||
}
|
||||
} else {
|
||||
console.error('카트 추가 실패:', addResult.error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 시나리오 2: 타임아웃이 있는 API 호출
|
||||
|
||||
```javascript
|
||||
import { tAxiosToPromise, withTimeout } from '../utils/asyncActionUtils';
|
||||
|
||||
export const getLargeData = () => async (dispatch, getState) => {
|
||||
const result = await withTimeout(
|
||||
tAxiosToPromise(
|
||||
TAxios,
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_LARGE_DATA,
|
||||
{},
|
||||
{},
|
||||
{}
|
||||
),
|
||||
10000, // 10초 타임아웃
|
||||
'데이터 조회 시간이 초과되었습니다'
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
dispatch({ type: types.GET_LARGE_DATA, payload: result.data.data });
|
||||
} else if (result.error.code === 'TIMEOUT') {
|
||||
// 타임아웃 처리
|
||||
dispatch({ type: types.SHOW_TIMEOUT_MESSAGE });
|
||||
} else {
|
||||
// 기타 에러 처리
|
||||
console.error('조회 실패:', result.error);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 장점
|
||||
|
||||
1. **성공 기준 명확화**: HTTP + retCode 모두 확인
|
||||
2. **체인 보장**: reject 없이 resolve만 사용하여 Promise 체인 유지
|
||||
3. **상세한 로깅**: 모든 단계에서 로그 출력
|
||||
4. **타임아웃 지원**: 응답 없는 API 처리 가능
|
||||
5. **에러 처리**: 모든 에러를 표준 구조로 반환
|
||||
|
||||
## ⚠️ 주의사항
|
||||
|
||||
1. **Chrome 68 호환**: async/await 사용 가능하지만 주의 필요
|
||||
2. **항상 resolve**: reject 사용하지 않음
|
||||
3. **success 플래그**: 반드시 `result.success` 확인 필요
|
||||
|
||||
---
|
||||
|
||||
**다음**: [해결 방법 3: 큐 기반 패널 액션 시스템 →](./04-solution-queue-system.md)
|
||||
626
.docs/dispatch-async/04-solution-queue-system.md
Normal file
626
.docs/dispatch-async/04-solution-queue-system.md
Normal file
@@ -0,0 +1,626 @@
|
||||
# 해결 방법 3: 큐 기반 패널 액션 시스템
|
||||
|
||||
## 📦 개요
|
||||
|
||||
**관련 파일**:
|
||||
- `src/actions/queuedPanelActions.js`
|
||||
- `src/middleware/panelQueueMiddleware.js`
|
||||
- `src/reducers/panelReducer.js`
|
||||
|
||||
**작성일**: 2025-11-06
|
||||
**커밋**:
|
||||
- `5bd2774 [251106] feat: Queued Panel functions`
|
||||
- `f9290a1 [251106] fix: Dispatch Queue implementation`
|
||||
|
||||
미들웨어 기반의 **액션 큐 처리 시스템**으로, 패널 액션들을 순차적으로 실행합니다.
|
||||
|
||||
## 🎯 핵심 개념
|
||||
|
||||
### 왜 큐 시스템이 필요한가?
|
||||
|
||||
패널 관련 액션들은 특히 순서가 중요합니다:
|
||||
|
||||
```javascript
|
||||
// 문제 상황
|
||||
dispatch(pushPanel({ name: 'SEARCH' })); // 검색 패널 열기
|
||||
dispatch(updatePanel({ results: [...] })); // 검색 결과 업데이트
|
||||
dispatch(popPanel('LOADING')); // 로딩 패널 닫기
|
||||
|
||||
// 실제 실행 순서 (문제!)
|
||||
// → popPanel이 먼저 실행될 수 있음
|
||||
// → updatePanel이 pushPanel보다 먼저 실행될 수 있음
|
||||
```
|
||||
|
||||
### 큐 시스템의 동작 방식
|
||||
|
||||
```
|
||||
[큐에 추가] → [미들웨어 감지] → [순차 처리] → [완료]
|
||||
↓ ↓ ↓ ↓
|
||||
ENQUEUE 자동 감지 시작 PROCESS_QUEUE 다음 액션
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 주요 컴포넌트
|
||||
|
||||
### 1. queuedPanelActions.js
|
||||
|
||||
패널 액션을 큐에 추가하는 액션 크리에이터들
|
||||
|
||||
### 2. panelQueueMiddleware.js
|
||||
|
||||
큐에 액션이 추가되면 자동으로 처리를 시작하는 미들웨어
|
||||
|
||||
### 3. panelReducer.js
|
||||
|
||||
큐 상태를 관리하는 리듀서
|
||||
|
||||
---
|
||||
|
||||
## 📋 기본 패널 액션
|
||||
|
||||
### 1. pushPanelQueued
|
||||
|
||||
패널을 큐에 추가하여 순차적으로 열기
|
||||
|
||||
```javascript
|
||||
import { pushPanelQueued } from '../actions/queuedPanelActions';
|
||||
|
||||
// 기본 사용
|
||||
dispatch(pushPanelQueued(
|
||||
{ name: panel_names.SEARCH_PANEL },
|
||||
false // duplicatable
|
||||
));
|
||||
|
||||
// 중복 허용
|
||||
dispatch(pushPanelQueued(
|
||||
{ name: panel_names.PRODUCT_DETAIL, productId: 123 },
|
||||
true // 중복 허용
|
||||
));
|
||||
```
|
||||
|
||||
### 2. popPanelQueued
|
||||
|
||||
패널을 큐를 통해 제거
|
||||
|
||||
```javascript
|
||||
import { popPanelQueued } from '../actions/queuedPanelActions';
|
||||
|
||||
// 마지막 패널 제거
|
||||
dispatch(popPanelQueued());
|
||||
|
||||
// 특정 패널 제거
|
||||
dispatch(popPanelQueued(panel_names.SEARCH_PANEL));
|
||||
```
|
||||
|
||||
### 3. updatePanelQueued
|
||||
|
||||
패널 정보를 큐를 통해 업데이트
|
||||
|
||||
```javascript
|
||||
import { updatePanelQueued } from '../actions/queuedPanelActions';
|
||||
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.SEARCH_PANEL,
|
||||
panelInfo: {
|
||||
results: [...],
|
||||
totalCount: 100
|
||||
}
|
||||
}));
|
||||
```
|
||||
|
||||
### 4. resetPanelsQueued
|
||||
|
||||
모든 패널을 초기화
|
||||
|
||||
```javascript
|
||||
import { resetPanelsQueued } from '../actions/queuedPanelActions';
|
||||
|
||||
// 빈 패널로 초기화
|
||||
dispatch(resetPanelsQueued());
|
||||
|
||||
// 특정 패널들로 초기화
|
||||
dispatch(resetPanelsQueued([
|
||||
{ name: panel_names.HOME }
|
||||
]));
|
||||
```
|
||||
|
||||
### 5. enqueueMultiplePanelActions
|
||||
|
||||
여러 패널 액션을 한 번에 큐에 추가
|
||||
|
||||
```javascript
|
||||
import { enqueueMultiplePanelActions, pushPanelQueued, updatePanelQueued, popPanelQueued }
|
||||
from '../actions/queuedPanelActions';
|
||||
|
||||
dispatch(enqueueMultiplePanelActions([
|
||||
pushPanelQueued({ name: panel_names.SEARCH_PANEL }),
|
||||
updatePanelQueued({ name: panel_names.SEARCH_PANEL, panelInfo: { query: 'test' } }),
|
||||
popPanelQueued(panel_names.LOADING_PANEL)
|
||||
]));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 비동기 패널 액션
|
||||
|
||||
### 1. enqueueAsyncPanelAction
|
||||
|
||||
비동기 작업(API 호출 등)을 큐에 추가하여 순차 실행
|
||||
|
||||
**파일**: `src/actions/queuedPanelActions.js:173-199`
|
||||
|
||||
```javascript
|
||||
import { enqueueAsyncPanelAction } from '../actions/queuedPanelActions';
|
||||
|
||||
dispatch(enqueueAsyncPanelAction({
|
||||
id: 'search_products_123', // 고유 ID
|
||||
|
||||
// 비동기 액션 (TAxios 등)
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.SEARCH_PRODUCTS,
|
||||
{},
|
||||
{ keyword: 'test' },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
|
||||
// 성공 콜백
|
||||
onSuccess: (response) => {
|
||||
console.log('검색 성공:', response);
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.SEARCH_RESULT,
|
||||
results: response.data.results
|
||||
}));
|
||||
},
|
||||
|
||||
// 실패 콜백
|
||||
onFail: (error) => {
|
||||
console.error('검색 실패:', error);
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ERROR,
|
||||
message: error.message
|
||||
}));
|
||||
},
|
||||
|
||||
// 완료 콜백 (성공/실패 모두 호출)
|
||||
onFinish: (isSuccess, result) => {
|
||||
console.log('검색 완료:', isSuccess ? '성공' : '실패');
|
||||
},
|
||||
|
||||
// 타임아웃 (ms)
|
||||
timeout: 10000 // 10초
|
||||
}));
|
||||
```
|
||||
|
||||
### 동작 흐름
|
||||
|
||||
```
|
||||
1. enqueueAsyncPanelAction 호출
|
||||
↓
|
||||
2. ENQUEUE_ASYNC_PANEL_ACTION dispatch
|
||||
↓
|
||||
3. executeAsyncAction 자동 실행
|
||||
↓
|
||||
4. wrapAsyncAction으로 Promise 래핑
|
||||
↓
|
||||
5. withTimeout으로 타임아웃 적용
|
||||
↓
|
||||
6. 결과에 따라 onSuccess 또는 onFail 호출
|
||||
↓
|
||||
7. COMPLETE_ASYNC_PANEL_ACTION 또는 FAIL_ASYNC_PANEL_ACTION dispatch
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔗 API 호출 후 패널 액션
|
||||
|
||||
### createApiWithPanelActions
|
||||
|
||||
API 호출 후 여러 패널 액션을 자동으로 실행
|
||||
|
||||
**파일**: `src/actions/queuedPanelActions.js:355-394`
|
||||
|
||||
```javascript
|
||||
import { createApiWithPanelActions } from '../actions/queuedPanelActions';
|
||||
|
||||
dispatch(createApiWithPanelActions({
|
||||
// API 호출
|
||||
apiCall: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.SEARCH_PRODUCTS,
|
||||
{},
|
||||
{ keyword: 'laptop' },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
|
||||
// API 성공 후 실행할 패널 액션들
|
||||
panelActions: [
|
||||
// Plain action
|
||||
{ type: 'PUSH_PANEL', payload: { name: panel_names.SEARCH_PANEL } },
|
||||
|
||||
// Dynamic action (response 사용)
|
||||
(response) => updatePanelQueued({
|
||||
name: panel_names.SEARCH_PANEL,
|
||||
panelInfo: {
|
||||
results: response.data.results,
|
||||
totalCount: response.data.totalCount
|
||||
}
|
||||
}),
|
||||
|
||||
// 또 다른 패널 액션
|
||||
popPanelQueued(panel_names.LOADING_PANEL)
|
||||
],
|
||||
|
||||
// API 성공 콜백
|
||||
onApiSuccess: (response) => {
|
||||
console.log('API 성공:', response.data.totalCount, '개 검색됨');
|
||||
},
|
||||
|
||||
// API 실패 콜백
|
||||
onApiFail: (error) => {
|
||||
console.error('API 실패:', error);
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ERROR,
|
||||
message: '검색에 실패했습니다'
|
||||
}));
|
||||
}
|
||||
}));
|
||||
```
|
||||
|
||||
### 사용 예제: 상품 검색
|
||||
|
||||
```javascript
|
||||
export const searchProducts = (keyword) =>
|
||||
createApiWithPanelActions({
|
||||
apiCall: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.SEARCH_PRODUCTS,
|
||||
{},
|
||||
{ keyword },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
panelActions: [
|
||||
// 1. 로딩 패널 닫기
|
||||
popPanelQueued(panel_names.LOADING_PANEL),
|
||||
|
||||
// 2. 검색 결과 패널 열기
|
||||
(response) => pushPanelQueued({
|
||||
name: panel_names.SEARCH_RESULT,
|
||||
results: response.data.results
|
||||
}),
|
||||
|
||||
// 3. 검색 히스토리 업데이트
|
||||
(response) => updatePanelQueued({
|
||||
name: panel_names.SEARCH_HISTORY,
|
||||
panelInfo: { lastSearch: keyword }
|
||||
})
|
||||
],
|
||||
onApiSuccess: (response) => {
|
||||
console.log(`${response.data.totalCount}개의 상품을 찾았습니다`);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 비동기 액션 시퀀스
|
||||
|
||||
### createAsyncPanelSequence
|
||||
|
||||
여러 비동기 액션을 **순차적으로** 실행
|
||||
|
||||
**파일**: `src/actions/queuedPanelActions.js:401-445`
|
||||
|
||||
```javascript
|
||||
import { createAsyncPanelSequence } from '../actions/queuedPanelActions';
|
||||
|
||||
dispatch(createAsyncPanelSequence([
|
||||
// 첫 번째 비동기 액션
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_USER_INFO, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
console.log('사용자 정보 조회 성공');
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.USER_INFO,
|
||||
userInfo: response.data.data
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
console.error('사용자 정보 조회 실패:', error);
|
||||
}
|
||||
},
|
||||
|
||||
// 두 번째 비동기 액션 (첫 번째 완료 후 실행)
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
const userInfo = getState().user.info;
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_CART,
|
||||
{},
|
||||
{ mbrNo: userInfo.mbrNo },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
console.log('카트 정보 조회 성공');
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.USER_INFO,
|
||||
panelInfo: { cartCount: response.data.data.length }
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
console.error('카트 정보 조회 실패:', error);
|
||||
}
|
||||
},
|
||||
|
||||
// 세 번째 비동기 액션 (두 번째 완료 후 실행)
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_ORDERS, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
console.log('주문 정보 조회 성공');
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ORDER_LIST,
|
||||
orders: response.data.data
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
console.error('주문 정보 조회 실패:', error);
|
||||
// 실패 시 시퀀스 중단
|
||||
}
|
||||
}
|
||||
]));
|
||||
```
|
||||
|
||||
### 동작 흐름
|
||||
|
||||
```
|
||||
Action 1 실행 → 성공? → Action 2 실행 → 성공? → Action 3 실행
|
||||
↓ ↓
|
||||
실패 시 실패 시
|
||||
중단 중단
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ 미들웨어: panelQueueMiddleware
|
||||
|
||||
### 동작 원리
|
||||
|
||||
**파일**: `src/middleware/panelQueueMiddleware.js`
|
||||
|
||||
```javascript
|
||||
const panelQueueMiddleware = (store) => (next) => (action) => {
|
||||
const result = next(action);
|
||||
|
||||
// 큐에 액션이 추가되면 자동으로 처리 시작
|
||||
if (action.type === types.ENQUEUE_PANEL_ACTION) {
|
||||
console.log('[panelQueueMiddleware] 🚀 ACTION_ENQUEUED', {
|
||||
action: action.payload.action,
|
||||
queueId: action.payload.id,
|
||||
});
|
||||
|
||||
// setTimeout을 사용하여 현재 액션이 완전히 처리된 후에 큐 처리 시작
|
||||
setTimeout(() => {
|
||||
const currentState = store.getState();
|
||||
|
||||
if (currentState.panels) {
|
||||
// 이미 처리 중이 아니고 큐에 액션이 있으면 처리 시작
|
||||
if (!currentState.panels.isProcessingQueue &&
|
||||
currentState.panels.panelActionQueue.length > 0) {
|
||||
console.log('[panelQueueMiddleware] ⚡ STARTING_QUEUE_PROCESS');
|
||||
store.dispatch({ type: types.PROCESS_PANEL_QUEUE });
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// 큐 처리가 완료되고 남은 큐가 있으면 계속 처리
|
||||
if (action.type === types.PROCESS_PANEL_QUEUE) {
|
||||
setTimeout(() => {
|
||||
const currentState = store.getState();
|
||||
|
||||
if (currentState.panels) {
|
||||
// 처리 중이 아니고 큐에 남은 액션이 있으면 계속 처리
|
||||
if (!currentState.panels.isProcessingQueue &&
|
||||
currentState.panels.panelActionQueue.length > 0) {
|
||||
console.log('[panelQueueMiddleware] 🔄 CONTINUING_QUEUE_PROCESS');
|
||||
store.dispatch({ type: types.PROCESS_PANEL_QUEUE });
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
```
|
||||
|
||||
### 주요 특징
|
||||
|
||||
1. ✅ **자동 시작**: 큐에 액션 추가 시 자동으로 처리 시작
|
||||
2. ✅ **연속 처리**: 한 액션 완료 후 자동으로 다음 액션 처리
|
||||
3. ✅ **중복 방지**: 이미 처리 중이면 새로 시작하지 않음
|
||||
4. ✅ **로깅**: 모든 단계에서 로그 출력
|
||||
|
||||
---
|
||||
|
||||
## 📊 리듀서 상태 구조
|
||||
|
||||
### panelReducer.js의 큐 관련 상태
|
||||
|
||||
```javascript
|
||||
{
|
||||
panels: [], // 실제 패널 스택
|
||||
lastPanelAction: 'push', // 마지막 액션 타입
|
||||
|
||||
// 큐 관련 상태
|
||||
panelActionQueue: [ // 처리 대기 중인 큐
|
||||
{
|
||||
id: 'queue_item_1_1699999999999',
|
||||
action: 'PUSH_PANEL',
|
||||
panel: { name: 'SEARCH_PANEL' },
|
||||
duplicatable: false,
|
||||
timestamp: 1699999999999
|
||||
},
|
||||
// ...
|
||||
],
|
||||
|
||||
isProcessingQueue: false, // 큐 처리 중 여부
|
||||
queueError: null, // 큐 처리 에러
|
||||
|
||||
queueStats: { // 큐 통계
|
||||
totalProcessed: 0, // 총 처리된 액션 수
|
||||
failedCount: 0, // 실패한 액션 수
|
||||
averageProcessingTime: 0 // 평균 처리 시간 (ms)
|
||||
},
|
||||
|
||||
// 비동기 액션 상태
|
||||
asyncActions: { // 실행 중인 비동기 액션들
|
||||
'async_action_1': {
|
||||
id: 'async_action_1',
|
||||
status: 'pending', // 'pending' | 'success' | 'failed'
|
||||
timestamp: 1699999999999
|
||||
}
|
||||
},
|
||||
|
||||
completedAsyncActions: [ // 완료된 액션 ID들
|
||||
'async_action_1',
|
||||
'async_action_2'
|
||||
],
|
||||
|
||||
failedAsyncActions: [ // 실패한 액션 ID들
|
||||
'async_action_3'
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 실제 사용 시나리오
|
||||
|
||||
### 시나리오 1: 검색 플로우
|
||||
|
||||
```javascript
|
||||
export const performSearch = (keyword) => (dispatch) => {
|
||||
// 1. 로딩 패널 열기
|
||||
dispatch(pushPanelQueued({ name: panel_names.LOADING }));
|
||||
|
||||
// 2. 검색 API 호출 후 결과 표시
|
||||
dispatch(createApiWithPanelActions({
|
||||
apiCall: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'post', URLS.SEARCH, {}, { keyword }, onSuccess, onFail);
|
||||
},
|
||||
panelActions: [
|
||||
popPanelQueued(panel_names.LOADING),
|
||||
(response) => pushPanelQueued({
|
||||
name: panel_names.SEARCH_RESULT,
|
||||
results: response.data.results
|
||||
})
|
||||
]
|
||||
}));
|
||||
};
|
||||
```
|
||||
|
||||
### 시나리오 2: 다단계 결제 프로세스
|
||||
|
||||
```javascript
|
||||
export const processCheckout = (orderInfo) =>
|
||||
createAsyncPanelSequence([
|
||||
// 1단계: 주문 검증
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'post', URLS.VALIDATE_ORDER, {}, orderInfo, onSuccess, onFail);
|
||||
},
|
||||
onSuccess: () => {
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.CHECKOUT,
|
||||
panelInfo: { step: 1, status: 'validated' }
|
||||
}));
|
||||
}
|
||||
},
|
||||
|
||||
// 2단계: 결제 처리
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'post', URLS.PROCESS_PAYMENT, {}, orderInfo, onSuccess, onFail);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.CHECKOUT,
|
||||
panelInfo: { step: 2, paymentId: response.data.data.paymentId }
|
||||
}));
|
||||
}
|
||||
},
|
||||
|
||||
// 3단계: 주문 확정
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
const state = getState();
|
||||
const paymentId = state.panels.panels.find(p => p.name === panel_names.CHECKOUT)
|
||||
.panelInfo.paymentId;
|
||||
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.CONFIRM_ORDER,
|
||||
{},
|
||||
{ ...orderInfo, paymentId },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch(popPanelQueued(panel_names.CHECKOUT));
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ORDER_COMPLETE,
|
||||
orderId: response.data.data.orderId
|
||||
}));
|
||||
}
|
||||
}
|
||||
]);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 장점
|
||||
|
||||
1. **완벽한 순서 보장**: 큐 시스템으로 100% 순서 보장
|
||||
2. **자동 처리**: 미들웨어가 자동으로 큐 처리
|
||||
3. **비동기 지원**: API 호출 등 비동기 작업 완벽 지원
|
||||
4. **타임아웃**: 응답 없는 작업 자동 처리
|
||||
5. **에러 복구**: 에러 발생 시에도 다음 액션 계속 처리
|
||||
6. **통계**: 큐 처리 통계 자동 수집
|
||||
|
||||
## ⚠️ 주의사항
|
||||
|
||||
1. **미들웨어 등록**: store에 panelQueueMiddleware 등록 필요
|
||||
2. **리듀서 확장**: panelReducer에 큐 관련 상태 추가 필요
|
||||
3. **기존 코드**: 기존 pushPanel 등과 병행 사용 가능
|
||||
|
||||
---
|
||||
|
||||
**다음**: [사용 패턴 및 예제 →](./05-usage-patterns.md)
|
||||
790
.docs/dispatch-async/05-usage-patterns.md
Normal file
790
.docs/dispatch-async/05-usage-patterns.md
Normal file
@@ -0,0 +1,790 @@
|
||||
# 사용 패턴 및 예제
|
||||
|
||||
## 📋 목차
|
||||
|
||||
1. [어떤 솔루션을 선택할까?](#어떤-솔루션을-선택할까)
|
||||
2. [공통 패턴](#공통-패턴)
|
||||
3. [실전 예제](#실전-예제)
|
||||
4. [마이그레이션 가이드](#마이그레이션-가이드)
|
||||
5. [Best Practices](#best-practices)
|
||||
|
||||
---
|
||||
|
||||
## 어떤 솔루션을 선택할까?
|
||||
|
||||
### 의사결정 플로우차트
|
||||
|
||||
```
|
||||
패널 관련 액션인가?
|
||||
├─ YES → 큐 기반 패널 액션 시스템 사용
|
||||
│ (queuedPanelActions.js)
|
||||
│
|
||||
└─ NO → API 호출이 포함되어 있는가?
|
||||
├─ YES → API 패턴은?
|
||||
│ ├─ API 후 여러 dispatch 필요 → createApiThunkWithChain
|
||||
│ ├─ 로딩 상태 관리 필요 → withLoadingState
|
||||
│ └─ Promise 기반 처리 필요 → asyncActionUtils
|
||||
│
|
||||
└─ NO → 순차적 dispatch만 필요
|
||||
→ createSequentialDispatch
|
||||
```
|
||||
|
||||
### 솔루션 비교표
|
||||
|
||||
| 상황 | 추천 솔루션 | 파일 |
|
||||
|------|------------|------|
|
||||
| 패널 열기/닫기/업데이트 | `pushPanelQueued`, `popPanelQueued` | queuedPanelActions.js |
|
||||
| API 호출 후 패널 업데이트 | `createApiWithPanelActions` | queuedPanelActions.js |
|
||||
| 여러 API 순차 호출 | `createAsyncPanelSequence` | queuedPanelActions.js |
|
||||
| API 후 여러 dispatch | `createApiThunkWithChain` | dispatchHelper.js |
|
||||
| 로딩 상태 자동 관리 | `withLoadingState` | dispatchHelper.js |
|
||||
| 단순 순차 dispatch | `createSequentialDispatch` | dispatchHelper.js |
|
||||
| Promise 기반 API 호출 | `fetchApi`, `tAxiosToPromise` | asyncActionUtils.js |
|
||||
|
||||
---
|
||||
|
||||
## 공통 패턴
|
||||
|
||||
### 패턴 1: API 후 State 업데이트
|
||||
|
||||
#### Before
|
||||
```javascript
|
||||
export const getProductDetail = (productId) => (dispatch, getState) => {
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.GET_PRODUCT_DETAIL, payload: response.data.data });
|
||||
dispatch(getRelatedProducts(productId));
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_PRODUCT, {}, { productId }, onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
#### After (dispatchHelper)
|
||||
```javascript
|
||||
export const getProductDetail = (productId) =>
|
||||
createApiThunkWithChain(
|
||||
(d, gs, onS, onF) => TAxios(d, gs, 'get', URLS.GET_PRODUCT, {}, { productId }, onS, onF),
|
||||
[
|
||||
(response) => ({ type: types.GET_PRODUCT_DETAIL, payload: response.data.data }),
|
||||
getRelatedProducts(productId)
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
#### After (asyncActionUtils - Chrome 68+)
|
||||
```javascript
|
||||
export const getProductDetail = (productId) => async (dispatch, getState) => {
|
||||
const result = await tAxiosToPromise(
|
||||
TAxios, dispatch, getState, 'get', URLS.GET_PRODUCT, {}, { productId }
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
dispatch({ type: types.GET_PRODUCT_DETAIL, payload: result.data.data });
|
||||
dispatch(getRelatedProducts(productId));
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 패턴 2: 로딩 상태 관리
|
||||
|
||||
#### Before
|
||||
```javascript
|
||||
export const fetchUserData = (userId) => (dispatch, getState) => {
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: true } }));
|
||||
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.GET_USER_DATA, payload: response.data.data });
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
};
|
||||
|
||||
const onFail = (error) => {
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_USER, {}, { userId }, onSuccess, onFail);
|
||||
};
|
||||
```
|
||||
|
||||
#### After
|
||||
```javascript
|
||||
export const fetchUserData = (userId) =>
|
||||
withLoadingState(
|
||||
(dispatch, getState) => {
|
||||
return TAxiosPromise(dispatch, getState, 'get', URLS.GET_USER, {}, { userId })
|
||||
.then((response) => {
|
||||
dispatch({ type: types.GET_USER_DATA, payload: response.data.data });
|
||||
});
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### 패턴 3: 패널 순차 열기
|
||||
|
||||
#### Before
|
||||
```javascript
|
||||
dispatch(pushPanel({ name: panel_names.SEARCH }));
|
||||
setTimeout(() => {
|
||||
dispatch(updatePanel({ results: [...] }));
|
||||
setTimeout(() => {
|
||||
dispatch(popPanel(panel_names.LOADING));
|
||||
}, 0);
|
||||
}, 0);
|
||||
```
|
||||
|
||||
#### After
|
||||
```javascript
|
||||
dispatch(enqueueMultiplePanelActions([
|
||||
pushPanelQueued({ name: panel_names.SEARCH }),
|
||||
updatePanelQueued({ results: [...] }),
|
||||
popPanelQueued(panel_names.LOADING)
|
||||
]));
|
||||
```
|
||||
|
||||
### 패턴 4: 조건부 dispatch
|
||||
|
||||
#### Before
|
||||
```javascript
|
||||
export const checkAndFetch = () => (dispatch, getState) => {
|
||||
const state = getState();
|
||||
|
||||
if (state.user.isLoggedIn) {
|
||||
dispatch(fetchUserProfile());
|
||||
dispatch(fetchUserCart());
|
||||
} else {
|
||||
dispatch({ type: types.SHOW_LOGIN_POPUP });
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### After
|
||||
```javascript
|
||||
export const checkAndFetch = () =>
|
||||
createConditionalDispatch(
|
||||
(state) => state.user.isLoggedIn,
|
||||
[
|
||||
fetchUserProfile(),
|
||||
fetchUserCart()
|
||||
],
|
||||
[
|
||||
{ type: types.SHOW_LOGIN_POPUP }
|
||||
]
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 실전 예제
|
||||
|
||||
### 예제 1: 검색 기능
|
||||
|
||||
```javascript
|
||||
// src/actions/searchActions.js
|
||||
import { createApiWithPanelActions, pushPanelQueued, popPanelQueued, updatePanelQueued }
|
||||
from './queuedPanelActions';
|
||||
import { panel_names } from '../constants/panelNames';
|
||||
import { URLS } from '../constants/urls';
|
||||
|
||||
export const performSearch = (keyword) => (dispatch) => {
|
||||
// 1. 로딩 패널 열기
|
||||
dispatch(pushPanelQueued({ name: panel_names.LOADING }));
|
||||
|
||||
// 2. 검색 API 호출 후 결과 처리
|
||||
dispatch(createApiWithPanelActions({
|
||||
apiCall: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.SEARCH_PRODUCTS,
|
||||
{},
|
||||
{ keyword, page: 1, size: 20 },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
|
||||
panelActions: [
|
||||
// 1) 로딩 패널 닫기
|
||||
popPanelQueued(panel_names.LOADING),
|
||||
|
||||
// 2) 검색 결과 패널 열기
|
||||
(response) => pushPanelQueued({
|
||||
name: panel_names.SEARCH_RESULT,
|
||||
results: response.data.results,
|
||||
totalCount: response.data.totalCount,
|
||||
keyword
|
||||
}),
|
||||
|
||||
// 3) 검색 히스토리 업데이트
|
||||
(response) => updatePanelQueued({
|
||||
name: panel_names.SEARCH_HISTORY,
|
||||
panelInfo: {
|
||||
lastSearch: keyword,
|
||||
resultCount: response.data.totalCount
|
||||
}
|
||||
})
|
||||
],
|
||||
|
||||
onApiSuccess: (response) => {
|
||||
console.log(`"${keyword}" 검색 완료: ${response.data.totalCount}개`);
|
||||
},
|
||||
|
||||
onApiFail: (error) => {
|
||||
console.error('검색 실패:', error);
|
||||
dispatch(popPanelQueued(panel_names.LOADING));
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ERROR,
|
||||
message: '검색에 실패했습니다'
|
||||
}));
|
||||
}
|
||||
}));
|
||||
};
|
||||
```
|
||||
|
||||
### 예제 2: 장바구니 추가
|
||||
|
||||
```javascript
|
||||
// src/actions/cartActions.js
|
||||
import { createApiThunkWithChain } from '../utils/dispatchHelper';
|
||||
import { types } from './actionTypes';
|
||||
import { URLS } from '../constants/urls';
|
||||
|
||||
export const addToCart = (productId, quantity) =>
|
||||
createApiThunkWithChain(
|
||||
// API 호출
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.ADD_TO_CART,
|
||||
{},
|
||||
{ productId, quantity },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
|
||||
// 성공 시 순차 dispatch
|
||||
[
|
||||
// 1) 장바구니 추가 액션
|
||||
(response) => ({
|
||||
type: types.ADD_TO_CART,
|
||||
payload: response.data.data
|
||||
}),
|
||||
|
||||
// 2) 장바구니 개수 업데이트
|
||||
(response) => ({
|
||||
type: types.UPDATE_CART_COUNT,
|
||||
payload: response.data.data.cartCount
|
||||
}),
|
||||
|
||||
// 3) 장바구니 정보 재조회
|
||||
(response) => getMyCartInfo({ mbrNo: response.data.data.mbrNo }),
|
||||
|
||||
// 4) 성공 메시지 표시
|
||||
() => ({
|
||||
type: types.SHOW_TOAST,
|
||||
payload: { message: '장바구니에 담았습니다' }
|
||||
})
|
||||
],
|
||||
|
||||
// 실패 시 dispatch
|
||||
(error) => ({
|
||||
type: types.SHOW_ERROR,
|
||||
payload: { message: error.message || '장바구니 담기에 실패했습니다' }
|
||||
})
|
||||
);
|
||||
```
|
||||
|
||||
### 예제 3: 로그인 플로우
|
||||
|
||||
```javascript
|
||||
// src/actions/authActions.js
|
||||
import { createAsyncPanelSequence } from './queuedPanelActions';
|
||||
import { withLoadingState } from '../utils/dispatchHelper';
|
||||
import { panel_names } from '../constants/panelNames';
|
||||
import { types } from './actionTypes';
|
||||
import { URLS } from '../constants/urls';
|
||||
|
||||
export const performLogin = (userId, password) =>
|
||||
withLoadingState(
|
||||
createAsyncPanelSequence([
|
||||
// 1단계: 로그인 API 호출
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.LOGIN,
|
||||
{},
|
||||
{ userId, password },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
// 로그인 성공 - 토큰 저장
|
||||
dispatch({
|
||||
type: types.LOGIN_SUCCESS,
|
||||
payload: {
|
||||
token: response.data.data.token,
|
||||
userInfo: response.data.data.userInfo
|
||||
}
|
||||
});
|
||||
},
|
||||
onFail: (error) => {
|
||||
dispatch({
|
||||
type: types.SHOW_ERROR,
|
||||
payload: { message: '로그인에 실패했습니다' }
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 2단계: 사용자 정보 조회
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
const state = getState();
|
||||
const mbrNo = state.auth.userInfo.mbrNo;
|
||||
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_USER_INFO,
|
||||
{},
|
||||
{ mbrNo },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch({
|
||||
type: types.GET_USER_INFO,
|
||||
payload: response.data.data
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 3단계: 장바구니 정보 조회
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
const state = getState();
|
||||
const mbrNo = state.auth.userInfo.mbrNo;
|
||||
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'get',
|
||||
URLS.GET_CART,
|
||||
{},
|
||||
{ mbrNo },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch({
|
||||
type: types.GET_CART_INFO,
|
||||
payload: response.data.data
|
||||
});
|
||||
|
||||
// 로그인 완료 패널로 이동
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.LOGIN_COMPLETE
|
||||
}));
|
||||
}
|
||||
}
|
||||
]),
|
||||
{ loadingType: 'wait' }
|
||||
);
|
||||
```
|
||||
|
||||
### 예제 4: 다단계 폼 제출
|
||||
|
||||
```javascript
|
||||
// src/actions/formActions.js
|
||||
import { createAsyncPanelSequence } from './queuedPanelActions';
|
||||
import { tAxiosToPromise } from '../utils/asyncActionUtils';
|
||||
import { types } from './actionTypes';
|
||||
import { URLS } from '../constants/urls';
|
||||
|
||||
export const submitMultiStepForm = (formData) =>
|
||||
createAsyncPanelSequence([
|
||||
// Step 1: 입력 검증
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.VALIDATE_FORM,
|
||||
{},
|
||||
formData,
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch({
|
||||
type: types.UPDATE_FORM_STEP,
|
||||
payload: { step: 1, status: 'validated' }
|
||||
});
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.FORM_PANEL,
|
||||
panelInfo: { step: 1, validated: true }
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
dispatch({
|
||||
type: types.SHOW_VALIDATION_ERROR,
|
||||
payload: { errors: error.data?.errors || [] }
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Step 2: 중복 체크
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.CHECK_DUPLICATE,
|
||||
{},
|
||||
{ email: formData.email },
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch({
|
||||
type: types.UPDATE_FORM_STEP,
|
||||
payload: { step: 2, status: 'checked' }
|
||||
});
|
||||
dispatch(updatePanelQueued({
|
||||
name: panel_names.FORM_PANEL,
|
||||
panelInfo: { step: 2, duplicate: false }
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
dispatch({
|
||||
type: types.SHOW_ERROR,
|
||||
payload: { message: '이미 사용 중인 이메일입니다' }
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Step 3: 최종 제출
|
||||
{
|
||||
asyncAction: (dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(
|
||||
dispatch,
|
||||
getState,
|
||||
'post',
|
||||
URLS.SUBMIT_FORM,
|
||||
{},
|
||||
formData,
|
||||
onSuccess,
|
||||
onFail
|
||||
);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
dispatch({
|
||||
type: types.SUBMIT_FORM_SUCCESS,
|
||||
payload: response.data.data
|
||||
});
|
||||
|
||||
// 성공 패널로 이동
|
||||
dispatch(popPanelQueued(panel_names.FORM_PANEL));
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.SUCCESS_PANEL,
|
||||
message: '가입이 완료되었습니다'
|
||||
}));
|
||||
},
|
||||
onFail: (error) => {
|
||||
dispatch({
|
||||
type: types.SUBMIT_FORM_FAIL,
|
||||
payload: { error: error.message }
|
||||
});
|
||||
}
|
||||
}
|
||||
]);
|
||||
```
|
||||
|
||||
### 예제 5: 병렬 데이터 로딩
|
||||
|
||||
```javascript
|
||||
// src/actions/dashboardActions.js
|
||||
import { createParallelDispatch } from '../utils/dispatchHelper';
|
||||
import { executeParallelAsyncActions } from '../utils/asyncActionUtils';
|
||||
import { types } from './actionTypes';
|
||||
import { URLS } from '../constants/urls';
|
||||
|
||||
// 방법 1: dispatchHelper 사용
|
||||
export const loadDashboardData = () =>
|
||||
createParallelDispatch([
|
||||
fetchUserProfile(),
|
||||
fetchRecentOrders(),
|
||||
fetchRecommendations(),
|
||||
fetchNotifications()
|
||||
], { withLoading: true });
|
||||
|
||||
// 방법 2: asyncActionUtils 사용
|
||||
export const loadDashboardDataAsync = () => async (dispatch, getState) => {
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: true } }));
|
||||
|
||||
const results = await executeParallelAsyncActions([
|
||||
// 1. 사용자 프로필
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_PROFILE, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
|
||||
// 2. 최근 주문
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_RECENT_ORDERS, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
|
||||
// 3. 추천 상품
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_RECOMMENDATIONS, {}, {}, onSuccess, onFail);
|
||||
},
|
||||
|
||||
// 4. 알림
|
||||
(dispatch, getState, onSuccess, onFail) => {
|
||||
TAxios(dispatch, getState, 'get', URLS.GET_NOTIFICATIONS, {}, {}, onSuccess, onFail);
|
||||
}
|
||||
], { dispatch, getState });
|
||||
|
||||
// 각 결과 처리
|
||||
const [profileResult, ordersResult, recoResult, notiResult] = results;
|
||||
|
||||
if (profileResult.success) {
|
||||
dispatch({ type: types.GET_PROFILE, payload: profileResult.data.data });
|
||||
}
|
||||
|
||||
if (ordersResult.success) {
|
||||
dispatch({ type: types.GET_RECENT_ORDERS, payload: ordersResult.data.data });
|
||||
}
|
||||
|
||||
if (recoResult.success) {
|
||||
dispatch({ type: types.GET_RECOMMENDATIONS, payload: recoResult.data.data });
|
||||
}
|
||||
|
||||
if (notiResult.success) {
|
||||
dispatch({ type: types.GET_NOTIFICATIONS, payload: notiResult.data.data });
|
||||
}
|
||||
|
||||
dispatch(changeAppStatus({ showLoadingPanel: { show: false } }));
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 마이그레이션 가이드
|
||||
|
||||
### Step 1: 파일 import 변경
|
||||
|
||||
```javascript
|
||||
// Before
|
||||
import { pushPanel, popPanel, updatePanel } from '../actions/panelActions';
|
||||
|
||||
// After
|
||||
import { pushPanelQueued, popPanelQueued, updatePanelQueued }
|
||||
from '../actions/queuedPanelActions';
|
||||
import { createApiThunkWithChain, withLoadingState }
|
||||
from '../utils/dispatchHelper';
|
||||
```
|
||||
|
||||
### Step 2: 기존 코드 점진적 마이그레이션
|
||||
|
||||
```javascript
|
||||
// 1단계: 기존 코드 유지
|
||||
dispatch(pushPanel({ name: panel_names.SEARCH }));
|
||||
|
||||
// 2단계: 큐 버전으로 변경
|
||||
dispatch(pushPanelQueued({ name: panel_names.SEARCH }));
|
||||
|
||||
// 3단계: 여러 액션을 묶어서 처리
|
||||
dispatch(enqueueMultiplePanelActions([
|
||||
pushPanelQueued({ name: panel_names.SEARCH }),
|
||||
updatePanelQueued({ results: [...] })
|
||||
]));
|
||||
```
|
||||
|
||||
### Step 3: setTimeout 패턴 제거
|
||||
|
||||
```javascript
|
||||
// Before
|
||||
dispatch(action1());
|
||||
setTimeout(() => {
|
||||
dispatch(action2());
|
||||
setTimeout(() => {
|
||||
dispatch(action3());
|
||||
}, 0);
|
||||
}, 0);
|
||||
|
||||
// After
|
||||
dispatch(createSequentialDispatch([
|
||||
action1(),
|
||||
action2(),
|
||||
action3()
|
||||
]));
|
||||
```
|
||||
|
||||
### Step 4: API 패턴 개선
|
||||
|
||||
```javascript
|
||||
// Before
|
||||
const onSuccess = (response) => {
|
||||
dispatch({ type: types.ACTION_1, payload: response.data });
|
||||
dispatch(action2());
|
||||
dispatch(action3());
|
||||
};
|
||||
|
||||
TAxios(dispatch, getState, 'post', URL, {}, params, onSuccess, onFail);
|
||||
|
||||
// After
|
||||
dispatch(createApiThunkWithChain(
|
||||
(d, gs, onS, onF) => TAxios(d, gs, 'post', URL, {}, params, onS, onF),
|
||||
[
|
||||
(response) => ({ type: types.ACTION_1, payload: response.data }),
|
||||
action2(),
|
||||
action3()
|
||||
]
|
||||
));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. 명확한 에러 처리
|
||||
|
||||
```javascript
|
||||
// ✅ Good
|
||||
dispatch(createApiWithPanelActions({
|
||||
apiCall: (d, gs, onS, onF) => TAxios(d, gs, 'post', URL, {}, params, onS, onF),
|
||||
panelActions: [...],
|
||||
onApiSuccess: (response) => {
|
||||
console.log('API 성공:', response);
|
||||
},
|
||||
onApiFail: (error) => {
|
||||
console.error('API 실패:', error);
|
||||
dispatch(pushPanelQueued({
|
||||
name: panel_names.ERROR,
|
||||
message: error.message || '작업에 실패했습니다'
|
||||
}));
|
||||
}
|
||||
}));
|
||||
|
||||
// ❌ Bad - 에러 처리 없음
|
||||
dispatch(createApiWithPanelActions({
|
||||
apiCall: (d, gs, onS, onF) => TAxios(d, gs, 'post', URL, {}, params, onS, onF),
|
||||
panelActions: [...]
|
||||
}));
|
||||
```
|
||||
|
||||
### 2. 타임아웃 설정
|
||||
|
||||
```javascript
|
||||
// ✅ Good
|
||||
dispatch(enqueueAsyncPanelAction({
|
||||
asyncAction: (d, gs, onS, onF) => {
|
||||
TAxios(d, gs, 'post', URL, {}, params, onS, onF);
|
||||
},
|
||||
timeout: 10000, // 10초
|
||||
onFail: (error) => {
|
||||
if (error.code === 'TIMEOUT') {
|
||||
console.error('요청 시간 초과');
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// ❌ Bad - 타임아웃 없음 (무한 대기 가능)
|
||||
dispatch(enqueueAsyncPanelAction({
|
||||
asyncAction: (d, gs, onS, onF) => {
|
||||
TAxios(d, gs, 'post', URL, {}, params, onS, onF);
|
||||
}
|
||||
}));
|
||||
```
|
||||
|
||||
### 3. 로깅 활용
|
||||
|
||||
```javascript
|
||||
// ✅ Good - 상세한 로깅
|
||||
console.log('[SearchAction] 🔍 검색 시작:', keyword);
|
||||
|
||||
dispatch(createApiWithPanelActions({
|
||||
apiCall: (d, gs, onS, onF) => {
|
||||
TAxios(d, gs, 'post', URLS.SEARCH, {}, { keyword }, onS, onF);
|
||||
},
|
||||
onApiSuccess: (response) => {
|
||||
console.log('[SearchAction] ✅ 검색 성공:', response.data.totalCount, '개');
|
||||
},
|
||||
onApiFail: (error) => {
|
||||
console.error('[SearchAction] ❌ 검색 실패:', error);
|
||||
}
|
||||
}));
|
||||
```
|
||||
|
||||
### 4. 상태 검증
|
||||
|
||||
```javascript
|
||||
// ✅ Good - 상태 검증 후 실행
|
||||
export const performAction = () =>
|
||||
createConditionalDispatch(
|
||||
(state) => state.user.isLoggedIn && state.cart.items.length > 0,
|
||||
[proceedToCheckout()],
|
||||
[{ type: types.SHOW_LOGIN_POPUP }]
|
||||
);
|
||||
|
||||
// ❌ Bad - 검증 없이 바로 실행
|
||||
export const performAction = () => proceedToCheckout();
|
||||
```
|
||||
|
||||
### 5. 재사용 가능한 액션
|
||||
|
||||
```javascript
|
||||
// ✅ Good - 재사용 가능
|
||||
export const fetchDataWithLoading = (url, actionType) =>
|
||||
withLoadingState(
|
||||
(dispatch, getState) => {
|
||||
return TAxiosPromise(dispatch, getState, 'get', url, {}, {})
|
||||
.then((response) => {
|
||||
dispatch({ type: actionType, payload: response.data.data });
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// 사용
|
||||
dispatch(fetchDataWithLoading(URLS.GET_USER, types.GET_USER));
|
||||
dispatch(fetchDataWithLoading(URLS.GET_CART, types.GET_CART));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 체크리스트
|
||||
|
||||
### 기능 구현 전 확인사항
|
||||
|
||||
- [ ] 패널 관련 액션인가? → 큐 시스템 사용
|
||||
- [ ] API 호출이 포함되어 있는가? → createApiThunkWithChain 또는 createApiWithPanelActions
|
||||
- [ ] 로딩 상태 관리가 필요한가? → withLoadingState
|
||||
- [ ] 순차 실행이 필요한가? → createSequentialDispatch 또는 createAsyncPanelSequence
|
||||
- [ ] 타임아웃이 필요한가? → withTimeout 또는 timeout 옵션 설정
|
||||
|
||||
### 코드 리뷰 체크리스트
|
||||
|
||||
- [ ] setTimeout 사용 여부 확인
|
||||
- [ ] 에러 처리가 적절한가?
|
||||
- [ ] 로깅이 충분한가?
|
||||
- [ ] 타임아웃이 설정되어 있는가?
|
||||
- [ ] 상태 검증이 필요한가?
|
||||
- [ ] 재사용 가능한 구조인가?
|
||||
|
||||
---
|
||||
|
||||
**이전**: [← 해결 방법 3: 큐 기반 패널 액션 시스템](./04-solution-queue-system.md)
|
||||
**처음으로**: [← README](./README.md)
|
||||
96
.docs/dispatch-async/README.md
Normal file
96
.docs/dispatch-async/README.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Dispatch 비동기 처리 순서 보장 솔루션
|
||||
|
||||
## 📋 목차
|
||||
|
||||
1. [문제 상황](./01-problem.md)
|
||||
2. [해결 방법 1: dispatchHelper.js](./02-solution-dispatch-helper.md)
|
||||
3. [해결 방법 2: asyncActionUtils.js](./03-solution-async-utils.md)
|
||||
4. [해결 방법 3: 큐 기반 패널 액션 시스템](./04-solution-queue-system.md)
|
||||
5. [사용 패턴 및 예제](./05-usage-patterns.md)
|
||||
|
||||
## 🎯 개요
|
||||
|
||||
이 문서는 Redux-thunk 환경에서 여러 개의 dispatch를 순차적으로 실행할 때 순서가 보장되지 않는 문제를 해결하기 위해 구현된 솔루션들을 정리한 문서입니다.
|
||||
|
||||
## 🚀 주요 솔루션
|
||||
|
||||
### 1. dispatchHelper.js (2025-11-05)
|
||||
Promise 체인 기반의 dispatch 순차 실행 헬퍼 함수 모음
|
||||
|
||||
- `createSequentialDispatch`: 순차적 dispatch 실행
|
||||
- `createApiThunkWithChain`: API 후 dispatch 자동 체이닝
|
||||
- `withLoadingState`: 로딩 상태 자동 관리
|
||||
- `createConditionalDispatch`: 조건부 dispatch
|
||||
- `createParallelDispatch`: 병렬 dispatch
|
||||
|
||||
### 2. asyncActionUtils.js (2025-11-06)
|
||||
Promise 기반 비동기 액션 처리 및 성공/실패 기준 명확화
|
||||
|
||||
- API 성공 기준: HTTP 200-299 + retCode 0/'0'
|
||||
- 모든 비동기 작업을 Promise로 래핑
|
||||
- reject 없이 resolve + success 플래그 사용
|
||||
- 타임아웃 지원
|
||||
|
||||
### 3. 큐 기반 패널 액션 시스템 (2025-11-06)
|
||||
미들웨어 기반의 액션 큐 처리 시스템
|
||||
|
||||
- `queuedPanelActions.js`: 큐 기반 패널 액션
|
||||
- `panelQueueMiddleware.js`: 자동 큐 처리 미들웨어
|
||||
- `panelReducer.js`: 큐 상태 관리
|
||||
|
||||
## 📊 커밋 히스토리
|
||||
|
||||
```
|
||||
f9290a1 [251106] fix: Dispatch Queue implementation
|
||||
- asyncActionUtils.js 추가
|
||||
- queuedPanelActions.js 확장
|
||||
- panelReducer.js 확장
|
||||
|
||||
5bd2774 [251106] feat: Queued Panel functions
|
||||
- queuedPanelActions.js 초기 구현
|
||||
- panelQueueMiddleware.js 추가
|
||||
|
||||
9490d72 [251105] feat: dispatchHelper.js
|
||||
- createSequentialDispatch
|
||||
- createApiThunkWithChain
|
||||
- withLoadingState
|
||||
- createConditionalDispatch
|
||||
- createParallelDispatch
|
||||
```
|
||||
|
||||
## 📂 관련 파일
|
||||
|
||||
### Core Files
|
||||
- `src/utils/dispatchHelper.js`
|
||||
- `src/utils/asyncActionUtils.js`
|
||||
- `src/actions/queuedPanelActions.js`
|
||||
- `src/middleware/panelQueueMiddleware.js`
|
||||
- `src/reducers/panelReducer.js`
|
||||
|
||||
### Example Files
|
||||
- `src/actions/homeActions.js`
|
||||
- `src/actions/cartActions.js`
|
||||
|
||||
## 🔑 핵심 개선 사항
|
||||
|
||||
1. ✅ **순서 보장**: Promise 체인과 큐 시스템으로 dispatch 순서 보장
|
||||
2. ✅ **에러 처리**: reject 대신 resolve + success 플래그로 체인 보장
|
||||
3. ✅ **성공 기준 명확화**: HTTP 상태 + retCode 둘 다 확인
|
||||
4. ✅ **타임아웃 지원**: withTimeout으로 응답 없는 API 처리
|
||||
5. ✅ **로깅**: 모든 단계에서 상세한 로그 출력
|
||||
6. ✅ **호환성**: 기존 코드와 완전 호환 (선택적 사용 가능)
|
||||
|
||||
## 🎓 학습 자료
|
||||
|
||||
각 솔루션에 대한 자세한 설명은 개별 문서를 참고하세요.
|
||||
|
||||
- 기존 코드의 문제점이 궁금하다면 → [01-problem.md](./01-problem.md)
|
||||
- dispatchHelper 사용법이 궁금하다면 → [02-solution-dispatch-helper.md](./02-solution-dispatch-helper.md)
|
||||
- asyncActionUtils 사용법이 궁금하다면 → [03-solution-async-utils.md](./03-solution-async-utils.md)
|
||||
- 큐 시스템 사용법이 궁금하다면 → [04-solution-queue-system.md](./04-solution-queue-system.md)
|
||||
- 실제 사용 예제가 궁금하다면 → [05-usage-patterns.md](./05-usage-patterns.md)
|
||||
|
||||
---
|
||||
|
||||
**작성일**: 2025-11-10
|
||||
**최종 수정일**: 2025-11-10
|
||||
Reference in New Issue
Block a user