본문 바로가기

JavaScript/Web Development

[JavaScript] Promise Chaining

[Promise Chaining]

 

이처럼 fetch 함수에서 3번 콜백함수가 실행되면 4번 콜백함수가 이어서 실행되는데,

 

then 메소드 뒤에는 이런식으로 계속해서 then 메소드를 붙이는 것이 가능하다. 

 

 

다음 코드를 실행해보면,

console.log('시작!');

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('끝!');

이와 같은 결괏값을 가지는데, 이전 콜백의 return 값을 그대로 다음 콜백의 파라미터로 받아서 사용하고 있음.

user 객체에서 address 프로퍼티 추출 -> address 객체에서 geo 프로퍼티 추출 -> geo 객체에서 lat 프로퍼티 추출.

 

이처럼 promise 객체에 then 메소드를 여러개 붙이는 것을 Promise Chaining 이라고 한다.

 

 

Promise Chaining

then 메소드는 각각 별개의 Promise 객체를 리턴함.

promise 객체의 then 메소드가 새로운 promise 객체를 리턴하기 때문에, then 메소드 뒤에 계속해서 then 을 붙이는 것이 가능한 것.

 

then 메소드가 리턴한 promise 객체는, 가장 처음에는 pending 상태임.

이후, then 메소드로 등록한 콜백이 실행되고 콜백에서 어떤 값이 리턴되면, then 메소드가 리턴했던 promise 객체가 영향을 받음. 이 때, 콜백에서 어떤 값을 리턴하느냐에 따라 받는 영향이 달라진다.

 

(1) 콜백함수에서 promise 객체를 리턴하는 경우

then 메소드가 리턴했던 promise 객체는, 콜백함수가 return 한 promise 객체와 동일한 상태와 결과를 갖게 됨.

콜백이 리턴한 promise 객체에 따라, then 메소드가 리턴한 promise 객체가 영향을 받게 됨. (예: fulfilled -> fulfilled , rejected -> rejected)

 

(2) 콜백함수에서 promise 객체가 아닌 값을 리턴하는 경우 (숫자, 문자열, 일반객체)

then 메소드가 리턴했던 promise 객체는 fulfilled 상태가 되며, 콜백함수의 리턴값을 작업성공 결과로 갖게됨.