개발 도구 (Development Tools)/JavaScript

[JavaScript] 비동기 코드를 순차적으로 실행하도록 만드는 패턴들

BiCute 2023. 1. 26. 08:00
반응형

 

 

비동기 코드를 순차적으로 실행하는 방법에는 여러 가지가 있습니다.

다음은 이와 관련된 몇 가지 패턴입니다.

 

#1 Chaining Promises

Promise의 then 메서드를 사용하여 여러 비동기 작업을 함께 연결하여 순서대로 실행되도록 할 수 있습니다.

async function runSequentially() {
  await doSomethingAsync()
    .then(result => doSomethingElseAsync(result))
    .then(result => doThirdThingAsync(result));
}

 

 

 

#2 Async/Await

Promise가 완료될 때까지 await 키워드를 사용하여 비동기 함수의 실행을 일시 중지할 수 있습니다.

다음과 같이 작성하여 비동기 작업을 순차적으로 실행하는 데 사용할 수 있습니다.

async function runSequentially() {
  const result1 = await doSomethingAsync();
  const result2 = await doSomethingElseAsync(result1);
  const result3 = await doThirdThingAsync(result2);
}

 

 

 

#3 Sequential Async Iteration

비동기 순차 반복(Sequential Async Iteration)

for-await-of 루프를 사용하여 비동기로 반복되는 항목을 반복하며, 비동기 작업을 순차적으로 수행할 수 있습니다.

async function runSequentially() {
  const asyncIterable = getAsyncIterable();
  for await (const item of asyncIterable) {
    await doSomethingAsync(item);
  }
}

 

 

#4 Async Queues

비동기 대기열(Async Queues)

대기열 데이터 구조를 사용하여 비동기 작업을 보관하고 한 번에 하나씩 처리할 수 있습니다.

이는 async/await 또는 promise를 사용하여 구현할 수 있습니다.

async function runSequentially() {
  const queue = [];

  // 대기열에 비동기 작업 추가
  queue.push(doSomethingAsync());
  queue.push(doSomethingElseAsync());
  queue.push(doThirdThingAsync());

  // 대기열의 작업을 순차적으로 처리
  while (queue.length > 0) {
    const task = queue.shift();
    await task;
  }
}

 

 

 

#5 Sync-Async Wrapper

비동기 함수를 동기 코드로 감싸는 것으로 동기 코드의 흐름에서 비동기 함수를 더욱 쉽게 사용할 수 있습니다.

function runSequentially() {
  doSomethingAsync()
    .then(result => doSomethingElseAsync(result))
    .then(result => doThirdThingAsync(result))
    .then(() => {
      // 비동기 작업이 완료되면 동기 코드로 계속 진행합니다.
    });
}

 

 

 

반응형