[typescript] 비동기 작업의 결과를 다른 비동기 작업에서 활용하는 방법

TypeScript를 사용하여 프론트엔드 또는 백엔드에서 비동기 작업의 결과를 다른 비동기 작업에서 활용하는 방법에 대해 알아보겠습니다.

Promise Chaining

JavaScript와 TypeScript에서, Promise 체이닝을 사용하여 하나의 비동기 작업의 결과를 다른 비동기 작업에서 활용할 수 있습니다.

예를 들어, 다음과 같이 두 개의 비동기 작업을 연결하여 실행할 수 있습니다.

function asyncOperation1(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Result from asyncOperation1');
    }, 1000);
  });
}

function asyncOperation2(input: string): Promise<number> {
  return new Promise((resolve) => {
    // perform some async operation using the input
    resolve(input.length);
  });
}

asyncOperation1()
  .then((result) => asyncOperation2(result))
  .then((length) => {
    console.log(`Length of the result: ${length}`);
  });

위의 예제에서, asyncOperation1의 결과를 asyncOperation2에서 활용하기 위해 then을 사용하여 체이닝됩니다.

Async/Await

TypeScript 2.1부터 Async/Await 패턴을 지원합니다. Async/Await는 Promise 기반의 비동기 작업을 보다 간결하고 가독성 있게 작성할 수 있도록 해줍니다.

async function asyncTask() {
  let result1 = await asyncOperation1();
  let result2 = await asyncOperation2(result1);

  console.log(`Length of the result: ${result2}`);
}

asyncTask();

위의 예제에서, asyncTask 함수는 async 키워드를 사용하여 정의되었고, await 키워드를 사용하여 비동기 작업의 결과를 변수에 할당하며 연이어 사용합니다.

결론

TypeScript에서 비동기 작업의 결과를 다른 비동기 작업에서 활용하는 방법에 대해 알아보았습니다. Promise 체이닝과 Async/Await을 통해 가독성 있는 코드를 작성하고 유지보수성을 향상시킬 수 있습니다.

이러한 기능들은 TypeScript를 사용하여 프로젝트에서 비동기 작업을 다룰 때 매우 유용하며, 개발자들이 효율적으로 코드를 작성하고 관리할 수 있도록 도와줍니다.

참고: