카테고리 없음

[JavaScript] Promise chaining

공기반 코딩반 2023. 5. 25. 10:29
반응형

Promise Chaining

Promise 객체에 then 메소드를 연속적으로 붙이는 것

 

console.log('START!');

fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => response.text())
  .then((result) => {
    const users = JSON.parse(result);
    return users[0];
  })
  .then((user) => {
    console.log(user);
    const { address } = user;
    return address;
  })
  .then((address) => {
    console.log(address);
    const { geo } = address;
    return geo;
  })
  .then((geo) => {
    console.log(geo);
    const { lat } = geo;
    return lat;
  })
  .then((lat) => {
    console.log(lat);
  })
  
  
  
console.log('END');

 

Promise 객체는 fetch 함수가 리턴하는 하나 아닌가?

→ then 메소드가 새로운 Promise 객체를 리턴하기 때문

 그래서 then 메소드 뒤에 then을 붙여 나갈 수 있다.

 

 

 

  • then 메소드가 리턴한 Promise 객체는 pending 상태임.
  • then 메소드를 등록한 callback에서 리턴하면 then 메소드가 리턴하는 promise객체가 영향을 받음.
    • callback에서 Promise 객체를 리턴하는 경우:
      • then 메소드가 리턴하는 promise객체는 callback 리턴하는 promise 객체와 동일한 상태.
      • callback이 리턴한 Promise 객체가 fulfilled 상태 이면, then 메소드가 return 하는 Promise 객체도 fulfilled 상태가 된다(동일한 작업결과)
      •  callback이 리턴한 Promise 객체가 rejected 상태 이면, then 메소드가 return 하는 Promise 객체도 rejected 상태가 된다(동일한 작업결과) 
    • callback에서 숫자, 문자열, 일반 객체를 리턴하는 경우
      • then 메소드가 리턴했던 프로미스 객체는 fulfilled 상태가 되고 callback의 리턴값을 작업 성공 결과로 갖는다.

callback에서  Promise 객체를 리턴하는 경우

※ 빨간색 네모 박스가 callback 부분

 

callback에서  Promise 객체를 리턴하는 경우

 

callback에서 객체 아닌 값을 리턴하는 경우

 

 

 

 

 


fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => response.text())

callback에서 리턴한 Promise 객체가 fulfilled 이면 →  then 메소드가 return하는 Promise 객체도 fulfilled가 됨.

 

 

 

.then((result) => {
    const users = JSON.parse(result);
    return users[0];
  })

이 경우는 일반 객체 리턴 --> then 메소드가 리턴하는 Promise 객체는 fulfilled 상태가 됨.

 

 

 

 

Promise Chaining이 필요한 경우

: 순차적으로 비동기작업을 처리해야할 때

- 이전 Promise 객체가 처리되기 전까지 다음 Promise 객체가 처리될 수 없음.

 

 

then메소드가 리턴하는 Promise객체와 fetch에서 리턴(callback에서 리턴하는)하는 Promise 객체와 결과와 상태가 같게 된다.

 

 

 

 

fetch 함수에서 리턴한 Promise객체에 노란색 네모칸 then 메소드가 연결되었다는 것.

반응형