Programming/Web

[Javascript] map에서 async/await을 사용하기

stein 2022. 8. 29. 14:16

 여느날과 같이, 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/

 

How to use Async and Await with Array.prototype.map()

Using async/await combined with map() can be a little tricky. Find out how.

flaviocopes.com

 

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)
  }