여느날과 같이, js로 코딩을 하던 날, 계속 버그가 잡히지 않던 코드가 있었다. 로직상 문제는 없는데, 비동기 작업들이 원하는 순서로 실행되지 않았다. 체크를 위해서 아래와 같이 console.log를 순서대로 적어놨다.
const saveConsultSchedule = async () => {
console.log(0)
await tempAvailableTime.map(async (e) => {
console.log(1)
const res = await API.deleteConsultSchedule(e.scheduleId)
console.log(2)
return res
})
console.log(3)
}
분명히 async/await을 잘 걸었다고 생각했는데(과하면 과했지), console의 출력이 다음과 같이 찍히는 것을 확인했다.
map에서 함수를 async/await으로 불렀으니 문제가 없어야 할텐데 분명히 저 부분에서 비동기가 제대로 처리되지 않는다.
const saveConsultSchedule = async () => {
console.log(0)
await API.deleteConsultSchedule(tempAvailableTime[0].scheduleId)
console.log(2)
}
// API.js
async deleteConsultSchedule(shceduleId) {
const deleteRes = await this.Axios(`Something`)
console.log(1)
return deleteRes
},
그래서 위와 같이 코드를 수정해서 테스트하니 문제가 없는 것을 확인했고, map에서 asyn/await이 문제가 있는 것을 확신하게 되어서 구글링을 해보았다.
https://flaviocopes.com/javascript-async-await-array-map/
map을 쓴 코드는 Promise.all로 map함수를 감싸줘야한다.
수정하여 정상작동하는 코드는 다음과 같다.
const saveConsultSchedule = async () => {
console.log(0)
await Promise.all(tempAvailableTime.map(async (e) => {
console.log(1)
const res = await API.deleteConsultSchedule(e.scheduleId)
console.log(2)
return res
}))
console.log(3)
}
'Programming > Web' 카테고리의 다른 글
[WEB] Virtual DOM이란? (0) | 2022.03.27 |
---|---|
[Web, Nginx] "data url(base64 encoded) image" vs "image file" 그리고 nginx gzip (0) | 2022.02.03 |
[CSS] transition (0) | 2022.01.19 |
[Web] 검색을 위한 좋은 RESTful URL은 어떤걸까? (0) | 2022.01.19 |
Mediapipe를 활용한 vision-depending-display 제작: 에러모음(업데이트중) (0) | 2021.09.19 |