Post

Promise / Future에 대한 개념 정리

Promise / Future란?

  • Future는 미래에 실행이 완료될 것으로 예상되는 객체를 의미한다.

    • 따라서 아직 실행되지 않은 경우나, 실행 중이지만 아직 완료되지 않은 경우를 포함하는 개념임.
    • Future 객체에 요청한 값이 들어오기를 기다리는 동안 다른 연산을 수행할 수 있다.
  • Promise

Promise / Future 가 왜 필요한가?

Promise / Future가 왜 필요한지를 이해하려면, callback의 단점을 이해하고 있어야 한다.

1
2
3
4
5
6
7
8
9
10
11
function callbackStyle(resolve, reject) {
   const result = 10;
   const isSuccessful = true
isSuccessful ? resolve(result) : reject(-1);
   };


callbackStyle(function (result) {
   console.log(result);
   }, (e) => e);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getData() {
   return new Promise(function (resolve, reject) {
   const result = 10;
   const isSuccessful = true

isSuccessful ? resolve(result) : reject(-1);});
   }



**const pm = getData();** 
  
**const pm2 =** 
pm.then(function (result) {
   console.log(result);

**return result;** 
  })
.catch((e) => e));

  • 별 차이가 없어 보일지 몰라도, Promise는 “값”으로 다룰 수 있다 는 점에서 callback과 큰 차이가 있다.
    • Promise를 리턴하면서 다음 Promise로 값을 전달할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const pm = getData();
   pm.then(function (result) {
   console.log(result);

**return result + 5;** 
  })
.then(function (result) {
console.log(result);
});


//// 결과 ////
10
15

  • callback의 단점은, callback hell에 빠질 수 있다는 것이다.

    • 원인은

    callback 실행 결과를 외부로 리턴할 수 없어 서 callback 결과를 다루려면 callback 안에서 해결해야 하고, 결국 callback 안에 callback, ... 형식으로 계속 중첩해서 써내려가야 한다는 것.

    • 반면 Promise는 실행 결과 프로미스를 리턴해서 다음 then으로 전달 가능하기 때문에 같은 depth에서 chaining이 가능하다. callback hell 문제에서 벗어날 수 있다.
Callback Hell 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function add10(a, callback) {
   setTimeout(() => {
   callback(a + 10);
   }, 500);
   }
   add10(5, function(res) {
   add10(res, function(res) {
   add10(res, function(res) {
   add10(res, function(res) {
   // log(res);
   });
   });
   });
   });

Promise를 사용하면?
1
2
3
4
5
6
7
8
9
10
function add5(a) {
   return new Promise(resolve =>
   setTimeout(() => resolve(a + 5), 500));
   }
   
  const p1 = add5(5)
   .then(add5)
   .then(add5)
   .then(add5);

  • 이처럼 Promise는 비동기를 리턴이 가능한, “값”으로 다루는데 의미가 있다.
async, await를 사용하면 Promise 가독성이 훨씬 좋아짐!

[JS] async - await / Promise

This post is licensed under CC BY 4.0 by the author.