🔗 using async await and .then together
에러 핸들링을 위해async/await
후에 .then
을 사용했는데 뭔가 찜찜해서 구글링 했더니 여러 의견이 있었다. 좀 더 알아볼만한 주제
배열을 순회하면서async/await
를 사용하는 비동기 처리 코드를 반복해야 해서 ForEach
loop로 작성했는데 작동하지 않았다. for
나 for of
구문을 사용해야 한다는 것을 알게 됨
// deliveryGroup 배열을 순회하면서 postInboundDelivery를 dispatch한다.
const handleDeliveryGroup = async deliveryGroup => {
for (let idx = 0; idx < deliveryGroup.length; idx++) {
...
await dispatch(postInboundDelivery(selectedTask, matOutputs));
...
}
};
🔗 Using async/await with a forEach loop
🔗 JavaScript loops - how to handle async/await
복사 붙여넣기로 만들어진 중복 코드가 없도록 해야한다. 특히 .split(" ")[0]
처럼 하드코딩을 포함하는 부분은 추후 변경의 여지가 있는데, 모듈화 되어있지 않으면 변경 시 여러 곳을 수정해야 하고 디버깅도 어렵다. 모듈화 함수는 루트 레벨에 common(예시) 폴더를 생성하여 모아두는 것이 좋다.
// bad
// in controller.js
const iStockTypeCode = matchedItem.iStockTypeCode;
if (
iStockTypeCode === "01" ||
iStockTypeCode === "02" ||
iStockTypeCode === "04"
) {
...
}
// 위 코드가 두 군데 이상에서 중복 작성됨
// good
// in common.js
export const iStockRequired = iStockTypeCode => {
if (["01", "02", "04"].includes(iStockTypeCode)) {
return true;
}
return false;
};
// in controller.js
import { iStockRequired, ... } from "../common";
if (iStockRequired(matchedItem.iStockTypeCode)) {
...
}
변경될 수 있는 문자열이나 숫자는 상수로 관리한다.
// bad
if (itemCount.length > 10) {
dispatch(
addError(`제품별 분할 항목 제한을 초과할 수 없습니다.`)
);
return _dispatch(clearInput());
}
//good
const MAX_SPLIT_NUMBER = 10;
if (itemCount.length > MAX_SPLIT_NUMBER) {
dispatch(
addError(`제품별 분할 항목은 ${MAX_SPLIT_NUMBER}개를 초과할 수 없습니다.`)
);
return _dispatch(clearInput());
}
유지보수 효율성도 높이고 에러 메시지도 더 정확하게 작성할 수 있다.