Web/javascript
array.map 안에서의 async/await 사용하기
rockettttman
2022. 5. 1. 16:44
아래 코드와 같이 한 리스트 안의 데이터를 map으로 loop 돌면서 각 item의 데이터를 가지고 박스번호를 가지고오는 api를 호출하였다. 잘 될것이라고 예상하였으나 async/await을 사용하였음에도 불구하고 기다리지않고 바로 다음 loop를 수행하는 바람에 _inRow라는 데이터에 boxNo가 undefined로 찍히는 현상이 발생하였다. breakpoint를 찍어보면서 디버깅 해보니 await문을 기다리지 않고 map을 빠져나가는 바람에 boxNo에 그렇게 찍힌것으로 확인되어 구글링을 해보았다.
body.map(async (item) => {
------생략-------
} else if (msg == '박스 분할') {
//2개담기
const res = await OrderReleaseService.getBoxNo(item.item.odrNo, item.item.copy?item.item.boxNo:'');
_inRow.unshift(
{
abEdCd: item.item.abEdCd,
abWkAttr: item.item.abWkAttr,
bcd: item.item.bcd,
boxNo: res.result.boxNo,
-----생략---------
setGoods(
_inRow.concat(
goods.filter((item, index) =>
delRow.find((i) => i === index) !== undefined
? null
: item,
),
),
);
몇군데 찾아본 결과 body.map안의 익명함수가 async로 비동기 처리되어 빠져나갔고 api호출이 완료되면 이벤트 완료되어 다시 unshift문으로 되돌아오는 현상으로 확인되었다. 그래서 다른 블로그를 참조하여 아래와 같이 Promis.all, then을 통해 수행해 주었다.
Promise.all(
body.map(async (item) => {
......
} else if (msg == '박스 분할') {
//2개담기
const res = await OrderReleaseService.getBoxNo(item.item.odrNo, item.item.copy?item.item.boxNo:'');
_inRow.unshift(
...
{
abEdCd: item.item.abEdCd,
abWkAttr: item.item.abWkAttr,
bcd: item.item.bcd,
boxNo: res.result.boxNo,
...
},
);
}
})
).then(() => {
.......내용생략
} else if (msg == '박스 분할') {
...
setGoods(
_inRow.concat(
goods.filter((item, index) =>
delRow.find((i) => i === index) !== undefined
? null
: item,
),
),
); // 동일한 row 생성 , 생성된 row 상단으로
}
})