Promise 객체와 관련 메소드

웅평·2023년 7월 13일
0

promise 객체란?

어떤 작업에 관한 상태 정보를 갖고 있는 객체이다.

console.log('Start!');

fetch('https://www.google.com')
  .then((response) => response.text())
  .then((result) => { console.log(result); });

console.log('End'); 

fetch함수는 promise객체를 리턴하고 then은 해당 promise객체의 매소드 이다.

위의 코드를 보면 fetch함수는 서버에 리퀘스트를 보내고 리스폰을 받는 작업을 수행한다
이때 이 작업이 성공적으로 잘 완료될 수도 있고 실패할 수도 있다
이런 작업의 결과가 fetch함수가 리턴하는 promise 객체에 저장된다
그래서 fetch 함수가 리턴하는 promise객체를 보면 성공했는지 실패했는지 알 수 있다

promise 객체는 크게 3가지 중 하나의 상태를 가진다

  • pending : 작업이 진행 중
  • fulfilled : 작업이 성공적으로 완료
  • rejected : 작업이 실패

만약 작업이 성공해서 fulfilled 상태가 된다면 promise 객체는 그 작업의 성공 결과도 함께가진다
실패한다면 rejected 상태를 가지게 되고 작업의 실패 이유에 관한 정보를 갖는다

then 메소드
콜백을 등록하기 위해서 사용한다고 했던 then메소드는 promise 객체의 메소드이다
이 then메소드는 promise 객체가 pending상태에서 fulfilled 상태가 될 때 실행할 콜백을 등록하는 메소드이다.

그리고 리스폰스가 와서 promise 객체가 실제로 pending상태에서 fulfilled 상태가 되면 콜백이 등록해둔 실행이 되고 그 작업 성공 결과가 콜백의 파라미터로 넘어오게 된다

fetch가 실행되면 promise 상태가 pending 상태 되고 ->
then메소드를 통해 promise 상태가 fulfilled가 되었을 때 등록한 콜백 샐행 ->
그 결과가 콜백의 파라미터 ( ((response) => response.text()) )로 넘어간다

Promise Chaining

promise의 객체의 then 메소드를 연속적으로 붙이는 것을 Promise Chaining이라고 한다
then 메소드는 새로운 promise 객체를 리턴한다 그래서 then 뒤에 then을 붙일 수 있다

then 메소드가 리턴한 promise 객체는 처음에는 pending 상태인데 then 메소드를 등록한 콜백이 실행되고 리턴한 값에 따라 promise 객체가 영향을 받는다

promise 객체를 리턴하는 경우
콜백이 리턴한 promise 객체와 동일한 상태와 결과를 갖는다
fulfilled -> fulfilled, rejected -> rejected

promise 객체가 아닌 값을 리턴하는 경우
숫자, 문자열, 일반 객체를 리턴 할 경우 promise 객체는 fulfilled 상태가 된다

Promise Chaining이 필요한 경우는 비동기 작업을 순차적으로 수행해야 할 때 사용한다
예를들어 user1의 쓴 글 목록을 가져오려고 하는데 user1에 대한 정보 조회가 먼저 이뤄어져야 user1이 쓴 글 목록을 가져올 수 있다.

text, json 메소드

text 메소드
예를 들어 user를 출력하자고 예시를 들자

console.log('Start!');

fetch('https://www.google.com/users')
  .then((response) => response.text())
  .then((result) => {
    const users = JSON.parse(result);
    console.log(users)
  });
console.log('End'); 

fetch 함수로 리스폰스를 잘 받으면, response 객체의 text 메소드는 fulfilled 상태이면서 리스폰스의 바디에 있는 내용을 string 타입으로 변환한 값을 Promise 객체를 리턴한다.
fulfilled 결과는 string 타입인데 JSON 데이터라면 JSON 객체의 parse 메소드로 Deserialize를 해줘야한다.(JSON.parse(result);)

json 메소드

console.log('Start!');

fetch('https://www.google.com/users')
  .then((response) => response.json())
  .then((result) => {
    const users = JSON.parse(result);
    console.log(users)
  });
console.log('End'); 

fetch 함수로 리스폰스를 잘 받으면, response 객체의 json 메소드는, fulfilled 상태이면서, 리스폰스의 바디에 있는 JSON 데이터를 자바스크립트 객체로 Deserialize해서 생겨난 객체를 Promise 객체를 리턴한다

rejected 상태

console.log('Start!');

fetch('https://www.google.com')
  .then((response) => response.text(), (error) => { console.log(error); })
  .then((result) => { console.log(result); });

console.log('End'); 

rejected상태가 되면 실행할 콜백을 2번 째 파라미터로 넣어준다

catch 메소드

rejected상태가 될 때 catch 메소드를 쓰는 방법이 있다

console.log('Start!');

fetch('https://www.google.com')
  .then((response) => response.text())
  .catch((error) => { console.log(error); });
  .then((result) => { console.log(result); });

console.log('End'); 

catch 메소드는 then 메소드를 약간 변형시킨것이다.
아래 코드와 위의 코드는 같은 의미를 가진다.

console.log('Start!');

fetch('https://www.google.com')
  .then((response) => response.text())
  .then(undefined, (error) => { console.log(error); });
  .then((result) => { console.log(result); });

console.log('End'); 

catch메소드는 가장 마지막에 쓴다.
중간에 에러가 발생해도 대응할 수 있도록 하기위해서 마지막에 쓴다.

console.log('Start!');

fetch('https://www.google.com')
  .then((response) => response.text())
  .then((result) => { 
  	console.log(result);
    });
  .catch((error) => { console.log(error); });

console.log('End'); 

finally 메소드

promise 객체가 성공하든 실패하든 관계없이 항상 실행하고 싶은 콜백이 있을 경우 사용
catch 메소드보다 뒤에 작성한다

Promise 객체 생성

const p = new Promise((resolve, reject) => {
	setTimeout(() => { resolve('succes'); }, 1000); // fulfilled 상태
    setTimeout(() => { reject(new Error('fail')); }, 1000); // rejected 상태
});

p.then((res) => { console.log(res) }); // fulfilled 상태
p.catch((res) => { console.log(res) }); // rejected 상태

resolve, reject는 각각 fulfilled와 rejected 상태로 만드는 함수이다.

참고
코드잇

0개의 댓글