Promise 에 대한 이해

이한재·2023년 1월 19일
0

Promise 에 대한 이해의 필요성

node.js 로 express 웹 프레임워크를 사용하여 API 서버를 개발하는 중에
async 와 await 그리고 Promise 에 대한 이해의 필요성을 느꼈다.

이전 부터 javascript 의 가장 큰 특징은 비동기적인 처리 방식이라고 생각하고 있었지만
javascript 에서의 비동기 처리의 핵심인
callback 함수, async, await 그리고 Promise 에 대한 이해는 전혀 없었다.

그래서 생활코딩 유튜브와 구글링을 통해 Promise 에 대해 이해를 조금이나마 할 수 있었고 그에 대한 정리를 하려고 한다.

Promise 는 무엇일까

Promise
The Promise object
represents
the eventual completion (or failure) of an asynchronous operation
and its resulting value.

mdn 에 나와있는 Promise 에 대한 설명이다
기본적으로 Promise 는 객체이고 비동기 작업에 대한 성공과 실패를 표현하는 객체라고 이해했다.

그럼 이 부분에서 비동기적 처리를 하는 이유에 대해서 궁금해졌다
비동기적 처리를 하는 이유 2가지

  1. 어떤 명령에 대해서 언제 끝날지 모르거나
  2. 주가되는 작업이 아닐때

주로 네트워크 통신과 관련된 기능을 구현할 때 사용 된다고 한다.

Promise 에서 주로 사용하는 메서드 두가지가 있는것으로 판단했다

  1. then()
  2. catch()

두 메서드 모두 콜백 함수를 인자로 받으며
then 메서드는 Promise 에 대해서 성공처리를 하며
catch 메서드는 Promise 에 대해서 에러처리를 한다고 이해했다.

다음은 fetch 함수를 잉요하여 응답을 받는 코드이다.
fetch() 함수는 Promise() 객체를 반환하며 그에 대해서 각각 then, catch 메서드를 호출하는 코드이다.

const fetched = fetch('https://jsonplaceholder.typicode.com/posts')
fetched.then(function(response) {
  console.log('response:', response)
})

fetched.catch(function(error) {
  console.log('reason:', reason)
})

위의 코드를 다음과 같이 연속적으로 사용하여 코드를 간결하게 할수도 있다.

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    console.log('response:', response)
  })
  .catch(function(error) {
    console.log('error:', error)
  })

다음은 Promise Chaining 을 하는 코드이다.
첫번째 then 으로 response.json() 에 대하여 리턴된 Promise 객체를 Resolve (분해하다, 해결하다)
하기 위하여 두번째 then() 함수를 호출했다.

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(async function(response) {
    //console.log('response:', response)
    return response.json()
  })
  .catch(function(error) {
    console.log('error:', error)
  })
  .then(function(data) {
    console.log('data', data)
  })

다음은 nested Promise 라고 하는것인데 위 코드와 다르게 response.json() 을 리턴하지 않고 then(), catch() 구문이 계속해서 이어질 수 있는 구조이다.
이런식으로 코드를 짜게되면 가독성이 안좋아 질 수 있으므로 지양해야 할 것 이다

fetch('https://jsonplaceholderasdf.typicode.com/posts')
  .then(function(response) {
    response.json()
	    .then(function(data) {
	      console.log(data)
	    })
	    .catch(function(error) {
              console.log('error:', error)
	    })
  })
  .catch(function(error) {
    console.log('error:', error)
  })

Promise 를 사용하는 이유

비동기적인 처리를 할 때 그 작업이 성공했는지 실패했는지를 표준화된 방법으로 처리할 수 있도록 해준다.

성공했을때는 then() 메서드가 호출되어 Promise 객체를 Resolve 할것이고
실패했을때는 catch() 메서드가 호출되어 Promise 객체에 대해서 Reject 할 것이다

Promise 에 대한 이해를 돕기위한 그림

profile
이한재입니다

0개의 댓글