
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>;
}
위의 인터페이스의 내용을 정리하자면
Promise는 비동기 작업의 완료를 나타낸다.
받은 Promise의 응답이 fulfilled 이면 then 실행, rejected이면 catch 실행
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 메서드는 두 개의 제네릭 타입 매개변수 TResult1과 TResult2를 가집니다.TResult1의 기본값은 T입니다. 이는 Promise가 이행되었을 때의 값의 타입입니다.TResult2의 기본값은 never입니다. 이는 Promise가 거부되었을 때의 값의 타입입니다.onfulfilled?:
onfulfilled는 Promise가 이행되었을 때 실행되는 콜백 함수입니다.((value: T) => TResult1 | PromiseLike) | undefined | null입니다.value: T: 이행된 값의 타입입니다.TResult1 | PromiseLike: 이 콜백 함수는 TResult1 타입의 값을 반환하거나, PromiseLike 객체를 반환할 수 있습니다.?: 이 매개변수는 선택적이므로, 제공하지 않아도 됩니다.onrejected?:
onrejected는 Promise가 거부되었을 때 실행되는 콜백 함수입니다.((reason: any) => TResult2 | PromiseLike) | undefined | null입니다.reason: any: 거부된 이유의 타입입니다. 일반적으로 오류 객체가 전달됩니다.TResult2 | PromiseLike: 이 콜백 함수는 TResult2 타입의 값을 반환하거나, PromiseLike 객체를 반환할 수 있습니다.?: 이 매개변수도 선택적입니다.catch 코드
catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): 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
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
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의 결과로 Response 객체가 전달됩니다.Response 객체는 다음과 같은 주요 속성과 메서드를 포함합니다:ok: 요청이 성공적이었는지 여부를 나타내는 불리언 값.status: HTTP 응답 상태 코드 (예: 200, 404 등).statusText: 상태 코드에 대한 설명.headers: 응답 헤더를 나타내는 Headers 객체.json(): 응답 본문을 JSON으로 파싱하는 메서드 (또한 Promise를 반환).text(): 응답 본문을 텍스트로 변환하는 메서드 (또한 Promise를 반환).blob(): 응답 본문을 Blob 객체로 변환하는 메서드 (또한 Promise를 반환).
역시 갓,,,,