[JS] map에서 throw Error가 작동하지 않는 문제

hahaha·2021년 11월 14일
0

에러 상황

map 함수 내에서 에러가 throw 된 경우 catch로 넘어가지 않는 문제

문제 코드

try {
  items.map(i => {
    await this.itemService.create(i);
  }),
} catch(error) {
  // throw된 error가 잡히지 않음
  throw new BadRequestException(error.message);
}
  
// ItemService.js
const product = await this.productService.findByCode(i.product_code);
      
if (!product) {
	throw new BadRequestException('PRODUCT_NOT_EXIST');
}  

해결 방안

  • Promise.all 사용
    - 프로미스 하나라도 에러가 발생할 경우, 다른 프로미스의 성공여부에 상관없이 에러 발생
try {
  await Promise.all(
    items.map(async (i) => {
    	await this.itemService.create(i);
  	}),
  );
} catch(error) {
  // throw된 error가 잡힘
  throw new BadRequestException(error.message);
}
  • map, reduce 에서 await 함수를 실행하는 방법
    - mapreduce에서의 해결 방안이 각각 달랐다.
    - 자세히 포스팅 할 예정
profile
junior backend-developer 👶💻

0개의 댓글