본문 바로가기

■ Web개발/Javascript

map으로 fetch하기. await async

const promises = array.map((e: any) => api<any>('post', '/api', e))
const results = await Promise.all(promises)

 

위와 같이 map 으로 실행한 것을 promises에 두면

프로미스 내부의 api들은 동기로 실행이 됩니다.

 

만약 비동기로 하나하나 실행하고 싶으시다면

for(const item of array){
  const promises = array.map((e: any) => api<any>('post', '/api', e))
}

이런식으로 하면 됩니다.

 

다만 비동기로 실행할 경우 속도가 느리기 때문에 배열을 보내고 백엔드에서 처리하는 것을 추천합니다.