[JS] Promise

kub938·2024년 8월 11일
3

JavaScript

목록 보기
1/4
post-thumbnail

Promise란?

  • 비동기 작업을 처리하는데 사용되는 객체
  • 콜백함수를 연결 할 수 있는 이미 진행중인 프로세스를 나타냄

Promise의 상태

  • pending: 요청 진행중
  • fulfilled: 요청이 성공적으로 완료되어 응답이 수신됨
  • rejected: 요청 중 오류가 발생 했을 때

Promise의 흐름

Promise의 인터페이스 구조

Promise의 안쪽을 들어가보면 아래와 같은 인터페이스가 생성되어 있다.


 //비동기 작업의 완료를 나타냅니다
interface Promise<T> {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
     
     //번역
     /*
     * Promise의 이행 및/또는 거부에 대한 콜백을 연결합니다.
     * @param onfulfill 함수는 Promise가 이행될때 실행(콜백)됩니다.
     * @param onrejected 함수는 Promise가 거부될때 실행(콜백)됩니다.
     * @returns 콜백의 완료를 위해 Promise를 반환합니다.
     */
     
    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

    /**
     * Attaches a callback for only the rejection of the Promise.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of the callback.
     */
     
     /**
     * Promise에서 거부 응답이 왔을때만 콜백 첨부
     * @param rejected(거부) 응답이 오면 onrejected Promise 콜백
     * callback이 완료될때 Promise 반환
     */
    catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
  • 위의 인터페이스의 내용을 정리하자면

    1. Promise는 비동기 작업의 완료를 나타낸다.

    2. 받은 Promise의 응답이 fulfilled 이면 then 실행, rejected이면 catch 실행

    3. then의 코드

      • then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;

        • 코드해석

          1. then: then
          • then 메서드는 두 개의 제네릭 타입 매개변수 TResult1TResult2를 가집니다.
          • TResult1의 기본값은 T입니다. 이는 Promise가 이행되었을 때의 값의 타입입니다.
          • TResult2의 기본값은 never입니다. 이는 Promise가 거부되었을 때의 값의 타입입니다.
          2. onfulfilled?:
          • onfulfilledPromise가 이행되었을 때 실행되는 콜백 함수입니다.
          • 타입은 ((value: T) => TResult1 | PromiseLike) | undefined | null입니다.
          • value: T: 이행된 값의 타입입니다.
          • TResult1 | PromiseLike: 이 콜백 함수는 TResult1 타입의 값을 반환하거나, PromiseLike 객체를 반환할 수 있습니다.
          • ?: 이 매개변수는 선택적이므로, 제공하지 않아도 됩니다.
          3. onrejected?:
          • onrejectedPromise가 거부되었을 때 실행되는 콜백 함수입니다.
          • 타입은 ((reason: any) => TResult2 | PromiseLike) | undefined | null입니다.
          • reason: any: 거부된 이유의 타입입니다. 일반적으로 오류 객체가 전달됩니다.
          • TResult2 | PromiseLike: 이 콜백 함수는 TResult2 타입의 값을 반환하거나, PromiseLike 객체를 반환할 수 있습니다.
          • ?: 이 매개변수도 선택적입니다.
      4. catch 코드
      • catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise;

Promise 객체 만들어 보기

  • 변수 inputData의 값 에 따라 resolve와 reject를 등록하고 출력하는 Promise 객체를 만들어 봤습니다
const myPromise = new Promise((resolve, reject) => {
    let inputData = true;
    if (inputData) {
        resolve("성공");
    }
    else {
        reject('실패');
    }
});

myPromise
    .then(success => console.log(success)) //성공 출력
    .catch(fail => console.log(fail))  // 실행x
		    
  • resolve와 reject 둘다 등록했을시의 출력값
const myPromise = new Promise((resolve, reject) => {
    resolve("성공");
    reject('실패');
});

myPromise
    .then(success => console.log(success))      //성공 출력
    .then(res => console.log(res))              //undefined 출력
    .catch(fail => console.log(fail))           //실행 x
  • 위 코드에서 undefined가 출력되는 이유
    • 첫번째 then에서 아무것도 return되지 않기 때문에 2번째 then에서 받는게 없기 때문
  • resolve와 reject를 모두 등록했지만 둘다 실행되지 않는 이유
    • then을 실행시키면 이 Promise는 이행 상태가 되기 때문에 그 이후부터는 아예 reject호출이 무시되어 catch문을 실행 시키지 않음

fetch의 응답값 Promise

fetch를 사용해서 받는 Promise는 fetch 함수 내부에서 생성된 Promise를 사용한다.

const fetchCheck = fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((response) => response.json())
    .then((json) => console.log(json))
    .catch(error => console.log('에러' + error));

console.log(fetchCheck)
  • fetch의 Promise 값을 fetchCheck 변수에 넣어서 console을 찍어보면 Promise의 형태를 볼 수 있다.
  • 위 사진을 보면 Promise가 fulfilled 상태로 잘 들어온 것을 볼 수 있고
  • 아래 응답으로 받은 결과값이 json으로도 잘 출력되는것을 볼 수 있다.
  • 이때 Promise<>의 상태와 PromiseState의 값이 다른 이유가 무엇일까?
    • <> 안의 값은 Promise가 생성된 직후의 상태를 나타냄
    • PromiseState는 비동기 작업이 완료된 후의 상태를 나타냄
    • 상태가 변경되는 시점과 console.log가 호출되는 시점이 다르기 때문에 서로 다른 결과를 나타냄
  • 추가적으로 위에서 만든 myPromise 객체의 출력값은 아래와 같다

fetch 응답 객체

  • fetch가 이행되면, Promise의 결과로 Response 객체가 전달됩니다.
  • Response 객체는 다음과 같은 주요 속성과 메서드를 포함합니다:
    • ok: 요청이 성공적이었는지 여부를 나타내는 불리언 값.
    • status: HTTP 응답 상태 코드 (예: 200, 404 등).
    • statusText: 상태 코드에 대한 설명.
    • headers: 응답 헤더를 나타내는 Headers 객체.
    • json(): 응답 본문을 JSON으로 파싱하는 메서드 (또한 Promise를 반환).
    • text(): 응답 본문을 텍스트로 변환하는 메서드 (또한 Promise를 반환).
    • blob(): 응답 본문을 Blob 객체로 변환하는 메서드 (또한 Promise를 반환).
profile
화면속에서 더 나은 경험을 제공하는 프론트엔드 개발자 김윤배 입니다

1개의 댓글

comment-user-thumbnail
2024년 8월 12일

역시 갓,,,,

답글 달기