본문 바로가기

JavaScript

[JavaScript] then vs Async/Await

자바스크립트로 개발을 하다보면 Promise 함수, 비동기 작업을 해야하는 경우가 많다. 

이때 습관적으로 Async/Await을 많이 사용한다. 

 

하지만 비동기 작업을 하기 위해서는 then이라는 친구도 있고 이 둘의 차이를 머리로는 알고 있지만 

따로 정리해본 적은 없어서 이번에 정리해보려고 한다. 

 

then 

console.log("1");

const promise = new Promise(function (resolve, reject) {
  setTimeout(() => {
    resolve("success");
  }, 1000);
});

console.log("2");

promise.then(function (value) {
  console.log(value);
});

console.log("3");

then을 사용해서 promise를 처리하는 코드를 작성해봤다. 

 

콘솔에서는 어떻게 찍히게 될까? 

1 => 2 => 3 => success 순으로 출력이 된다. 

 

즉, then은 호출되고 호출된 곳에서 작업을 멈추는 것이 아닌 통과하고 작업이 완료되면 콜백 함수가 호출된다. 

 

Async/Await 

async function test() {
  console.log("1");

  const promise = new Promise(function (resolve, reject) {
    setTimeout(() => {
      resolve("success");
    }, 1000);
  });

  console.log("2");

  async function promiseFunction() {
    const result = await promise;
    console.log(result);
  }

  await promiseFunction();

  console.log("3");
}

test();

하지만 Async/Await을 사용하면 1 => 2 => success => 3 순으로 출력이 된다. 

Async/Await은 호출된 곳에서 비동기 작업이 종료될 때까지 기다렸다가 완료되면 다음 작업으로 넘어간다. 

 

지금까지 봤을 때 then과 Async/Await 중 Async/Await이 좀더 깔끔해보인다. 

그렇다면 모든 비동기 작업은 Async / Await을 사용하면 될까? 

 

then을 사용하는 경우 

일반적으로 비동기 작업을 동기처럼 사용하는 경우에는 Async / Await을 사용하면 된다. 

하지만 Promise가 실행되는 시점후속 작업을 하는 시점을 달리해야한다면 then을 사용한다. 

 

Promise.all의 경우가 이런 경우이다. 

일반적으로 유저를 조회하고 해당 유저의 ID로 구매 정보를 가지고 온다면 Async / Await이 더 편할 것이다. 

하지만 유저 리스트를 조회하고 상품 리스트를 조회하는 경우에는 어떨까? 

이런 작업 순서와 무관한 비동기 작업을 병렬로 진행하는 상황이 있을 수 있다. 

const promise1 = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 1000);
  });

const promise2 = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 2000);
  });

const promise3 = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1);
    }, 3000);
  });

다음과 같이 순서와 무관한 비동기 함수가 3개가 있다고 생각하자. 

이것을 Async / Await으로 작업한다면 어떻게 될까? 

async function test() {
  await promise1();
  await promise2();
  await promise3();

  console.log("작업 완료");
}

test();

다음과 같은 방식으로 작성할 것이고 이것의 소요 시간은 얼마나 나올까? 

1초, 2초, 3초가 걸리는 작업을 순서대로 했기 때문에 일반적으로 6초가 나올 것이다. 

 

promise1 = 1초 => promise2 = 2초 => promise3 = 3초 => " 작업 완료 "

 

하지만 Promise.all을 사용한다면? 

async function test() {
  await Promise.all([promise1(), promise2(), promise3()]);

  console.log("작업 완료");
}

test();

다음과 같이 작성할 것이며, 병렬로 작업을 진행되기 때문에 3초만에 모든 작업이 완료될 것이다. 

 

promise1 = 1초 =>

promise2 = 2초 ==>

promise3 = 3초 ===>

" 작업 완료 "

 

Promise.all이 아니더라도 promise를 단독으로 사용하는 경우에도 사용될 수 있다. 

반응형