아카이브

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

Frontend

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

Rayi 2024. 7. 26. 09:44

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

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

 

예를 들어 비동기 함수 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
Comments