Catalog
  1. 1. Promise
  2. 2. Async와 Await
Promise와 async await

Promise

promise는 함수가 아닌 객체로, 비동기 통신 이후에 순차적으로 여러 콜백함수를 실행시켜야 할 때의 복잡도와 예외처리의 어려움을 해결해준다.
promise는 비동기 함수를 감싸며, 통신 성공 여부에 따라 resolve() reject()함수를 실행시킬 수 있다.

1
const callAPI = new Promise(function(resolve, reject){
2
    //...비동기 로직
3
    if(response){ //통신이 성공할 경우
4
      resolve(response);
5
    }else{ //통신이 실패한 경우
6
      reject();
7
    }
8
});
9
10
//promise가 resolve()상태일 경우 then()를 이용하여 콜백함수를 실행시킬 수 있다.
11
callAPI().then(promise콜백).then(promise콜백).catch(통신실패 콜백함수)

promise에는 3가지 상태가 존재한다.

  • pending(대기) : new Promise를 하여 객체 생성상태
  • fulfill(이행,완료) : 호출성공 resolve()를 한 상태로, .then()를 이용하여 callback 절차를 시행할 수 있다. chain형태로 여러 promise객체를 연결하여 사용가능하다.
  • reject(실패) : 호출실패 reject(에러객체)를 한 상태로, .then().catch()를 이용하면 실패에 대한 예외처리도 할 수 있다.
    alt text

이제 promise를 이용하여 상단의 예제를 개선해보자.

1
const callAPI = function() {
2
  return new Promise(function(resolve, reject){
3
    const xhttp = new XMLHttpRequest();
4
    xhttp.onreadystatechange = function(response) {
5
      if(this.readyState === 4 && this.status === 200) {
6
        resolve(response); //API통신이 정상적으로 이루어진 경우 resolve()실행
7
      }else if(this.status !== 0 && this.status !== 200){
8
        reject({ error: "통신 오류발생!" }) //API통신이 실패한 경우 reject()실행, 에러에 대한 객체를 인자로 넘길 수 있다.
9
      };
10
    };
11
12
    xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
13
    xhttp.send();
14
  });
15
}
16
17
callAPI().then(function(response){
18
  console.log(response);
19
}).catch(function(error){
20
  console.log(error);
21
});

Async와 Await

async await문법은 최신 자바스크립트(ECMA2017)의 비동기 처리 패턴으로, 비동기 처리에 대하여 절차적인 프로그래밍이 가능하도록 가독성을 높인 문법이다.
사용방법은 비동기 로직들을 실행할 외부함수에 예약어 async을 붙여주고, 내부 비동기 처리함수에 예약어 await를 붙여주면 된다.

주의할 점은 await의 예약어가 붙은 함수는 promise 객체를 꼭 반환해주어야 한다.
예외처리는 javascript의 try{}catch(){} 문법을 적용하도록 하자.

그렇다면 Promise와 어떠한 차이가 있는지 예제로 비교해보자.

1
2
const callAPI = function() {
3
  return new Promise(function(resolve, reject){
4
    //비동기 로직
5
    resolve(response);
6
  })
7
}
8
9
const otherAPI = function(param) {
10
  return new Promise(function(resolve, reject){
11
    //비동기 로직
12
    resolve(response);
13
  })
14
}
15
16
const anotherAPI = function(param) {
17
  return new Promise(function(resolve, reject) {
18
    //비동기 로직
19
    resolve(response);
20
  })
21
}
22
23
//Promise
24
callAPI().then(function(response) {
25
  return otherAPI(response);
26
}).then(function(response) {
27
  return anotherAPI(response);
28
}).then(function(result) {
29
  console.log(result)
30
}).catch(function(error){
31
  console.log(error);
32
})
33
34
//async await
35
const playLogic = async function() {
36
  try {
37
    const callRes = await callAPI();
38
    const otherRes = await otherAPI(callRes);
39
    const result = await anotherAPI(otherRes);
40
    console.log(result);
41
  } catch(error) {
42
    console.log(error)
43
  }
44
}
45
46
playLogic();

예제에서 Promise와 async await 로직을 비교해보자
확실히 await async문법이 Promise문법보다 직관적으로 일반적인 동기처리 코딩방식과 매우 유사하고, 가독성이 매우 좋다는 것을 느낄 수 있다.
개인적으로 특정 동기처리 로직에 다수의 비동기처리가 연관되어 있을 경우 async await문법의 장점이 부각될 것이라고 생각한다.

alt text


Comment