[Frontend] 효율적인 비동기 코드

2024. 7. 26. 09:44·Frontend

긴 시간이 필요한 작업들을 비동기 함수 안에서 처리하면 그 작업들이 실행되는 동안 비동기 함수 바깥의 다른 일들을 수행할 수 있습니다.

하지만 비동기 함수 내의 작업들이 많아질수록 비동기 함수의 처리 시간 자체가 길어져 병목이 될 우려가 있습니다.

 

예를 들어 비동기 함수 asyncFunc( )에서 fetch 함수를 10번 반복해서 실행하는 코드를 봅시다.

const asyncFunc = async () => {
	for (let i=0; i<10; i++) {
    	const res = await fetch(`http://.../${i}`)
        console.log(res)
    }
}

asyncFunc()

console.log("Job is done.")

이를 풀어서 다시 쓰면 다음과 같이 나타낼 수 있습니다.

const asyncFunc = async () => {
    const res = await fetch(`http://.../0`)  // 대기
    console.log(res)
    const res = await fetch(`http://.../1`)  // 대기
    console.log(res)
    const res = await fetch(`http://.../2`)  // 대기
    console.log(res)
    
    ...
    
    const res = await fetch(`http://.../9`)  // 대기
    console.log(res)
}

asyncFunc()

console.log("Job is done.")

비동기함수이기 때문에 fetch( )들이 실행되는 동안 바깥의 console.log( )가 먼저 실행될 수 있지만,

asyncFunc 자체는 fetch를 10번이나 기다려야 하므로 전체적으로 실행시간이 길어질 수 밖에 없습니다.

 

이를 좀 더 효율적으로 재구성하면, 다음과 같이 나타낼 수 있습니다.

const asyncFunc = async (i) => {
    const res = await fetch(`http://.../${i}`)
    console.log(res)
}

for (let i=0; i<10; i++) {
	asyncFunc(i)
}

console.log("Job is done.")

이번에는 비동기 함수 바깥에 반복문이 있습니다.

이를 풀어서 다시 쓰면 다음과 같이 나타낼 수 있습니다.

const asyncFunc = async (i) => {
    const res = await fetch(`http://.../${i}`)  // 대기
    console.log(res)
}

asyncFunc(0)  // 0이 실행되는 동안
asyncFunc(1)  // 1을 시작할 수 있습니다.
asyncFunc(2)

...

asyncFunc(9)

console.log("Job is done.")

이 경우 하나의 fetch를 실행하는 동안 다음 asyncFunc( )를 실행함으로서 다른 fetch도 함께 실행할 수 있기에,

이전 코드와 달리 여러개의 fetch를 동시에 실행할 수 있습니다.

단, fetch( )가 끝나는 지점 또한 모두 동일하기 때문에, console.log(res)의 출력 순서는 무작위로 나올 수 있습니다.

res1
res8
res6
res2
res5
res4
res7
res0
res9
res3
Job is done.

JavaScript의 경우, 이런 경우를 위해 Promise.all() 함수를 지원하고 있습니다.

728x90

'Frontend' 카테고리의 다른 글

[Three] Three.js에 대해서  (0) 2025.01.12
[TS] Could not find a declaration file for module '...' 해결하기  (0) 2024.12.19
[Frontend] 비동기 방식 (Asynchronous)  (0) 2024.07.22
[Frontend][Deploy] AWS로 프론트엔드 배포하기  (0) 2024.06.17
[Frontend] JSX에 대하여  (0) 2024.05.20
'Frontend' 카테고리의 다른 글
  • [Three] Three.js에 대해서
  • [TS] Could not find a declaration file for module '...' 해결하기
  • [Frontend] 비동기 방식 (Asynchronous)
  • [Frontend][Deploy] AWS로 프론트엔드 배포하기
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    figma
    GAN
    html
    Three
    CSS
    python
    backend
    ts
    ps
    review
    frontend
    ML
    PRISMA
    Git
    js
    C++
    CS
    postgresql
    PyTorch
    API
    UI
    react
    Express
    vscode
    DB
    nodejs
    mongo
    SOLID
    CV
    deploy
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[Frontend] 효율적인 비동기 코드
상단으로

티스토리툴바