본문 바로가기
Javascript

javascript Promise

by reo.l 2021. 2. 4.

전에 비동기에 대하여 배웠다.

비동기는 특정 코드의 연산이 끝날 때까지 코드의 실행을 멈추지 않고,

다음 코드를 먼저 실행하게 된다.

그렇다면 이러한 비동기를 제어하여 순서를 부여하기 위해서 어떻게 해야 할까?

 

const prinNum = (num) => {
  setTimeout(
    () => {
      console.log(num)
    }, 
    Math.floor(Math.random() * 100) + 1
  )
}

const printAll = () => {
  prinNum(1)
  prinNum(2)
  prinNum(3)
}
printAll()
printAll()
printAll()

// 123 231 132

 

숫자를 받아 랜덤 하게 비동기로 실행이 되어 숫자를 출력해주는 함수이다.

이를 실행하면 Math.random()에 의해서 순서가 바뀔 것이다.

이를 제어하기 위해 콜백 패턴을 사용한다.

 

const printNum = (num, callback) => {
  setTimeout(
    () => {
      console.log(num)
      callback()
    }, 
    Math.floor(Math.random() * 100) + 1
  )
}

const printAll = () => {
  printNum(1, () => {
    printNum(2, () => {
      printNum(3, () => {})
    })
  })
}
printAll()
printAll()
printAll()

// 123 123 123

 

이처럼 콜백 함수를 사용하여 비동기를 제어해줄 수 있다.

그러나 단점이 분명하다.

많은 콜백 함수를 사용할 시에 콜백 헬(콜백이 무수히 많음)에 빠질 수 있다.

또한 에러를 처리할 시에 콜백 함수에 에러 처리를 일일이 다 처리를 해줘야 하므로 굉장히 비효율 적이다.

이러한 문제점들을  보완하기 위해 es6이후 promise를 사용하게 됐다.

 

promise

promise는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타낸다.

promise는 생성자 함수로써 resolve, reject 함수를 매개변수로 하는

콜백 함수를 받아 비동기를 효율적으로 제어한다.

const printNum = (num) => {
  return new Promise((resolve, reject) => {
    setTimeout(
      () => {
        console.log(num)
        resolve()
      },
      Math.floor(Math.random() * 100) + 1
    )
  })
}

const printAll = () => {
  printNum(1)
    .then(() => {
      return printNum(2)
    })
    .then(() => {
      return printNum(3)
    })
}
printAll()

// 123

이와 같이 Promise 생성자 함수를 리턴하는 함수를 만들고

사용 시에는 then 등을 통해 후속 처리를 해준다. 

 

resolve, reject

콜백 함수의 매개변수인 함수 resolve, reject에 대하여 설명하겠다.

콜백 함수가 실행될 때 처리 성공 시 resolve 함수의 매개변수로

에러 발생 시 reject함수의 매개변수로 들어간다.

new Promise((resolve, reject) => {
  if (!err) {
    resolve('do something');
  } else {
    reject(err);
  }
})

 

 

then, catch

promise의 후속처리를 해주는 메서드인 then, catch에 대하여 설명하겠다. 

(후속처리를 통해 효율적으로 제어)

then은 resolve에 들어 간 값을 받아 나타낸다.

const promise = new Promise((resolve, reject) => {
  resolve("hello");
});

promise.then(value => console.log(value));
// hello

catch는 reject에 들어 간 값을 받아 나타낸다.

const promise = new Promise((resolve, reject) => {
  reject("err");
});

promise.then(value => console.log(value));
// UnhandledPromiseRejectionWarning: reject


promise.then(result => console.log(result)).catch(error => console.log(error));
//err

 

주의할 점은 reject시 then이 오면 에러가 발생한다.

이를 위해서 마지막에 catch처리를 해주면

콜백 패턴에서 일일이 에러 처리를 해줘야 했던 부분을 간결하게 해결할 수 있다.

간단하게 생각하면 resolve시에 then으로 가고 reject시에는 마지막의 catch로 가는 것이다.

 

 

마지막으로 promise는 세 가지 상태를 가지고 있다.

 

 

 

'Javascript' 카테고리의 다른 글

Redux  (0) 2021.03.01
javascript async / await  (0) 2021.02.10
javascript Object Oriented Programming (js-class)  (0) 2021.01.21
javascript Object Oriented Programming (js-prototype)  (0) 2021.01.19
javascript Object Oriented Programming  (0) 2021.01.17

댓글