본문 바로가기
Web/JavaScript

[JavaScript] Promise 객체 - 3️⃣ all(), allSettled(), race()

by coding-choonsik 2023. 4. 20.
728x90
반응형
SMALL

1. Promise 객체 콜백함수 실행

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise3</title>
</head>
<body>
    <h2>promise3</h2>
    <script>
        function getBanana(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍌')
                }, 1000)  // 1초후 바나나 이모지 
            })
        }

        function getApple(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍎')
                }, 3000)  // 3초후 사과 이모지 
            })
        }

        function getOrange(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍊')
                }, 4000)  // 4초후 오렌지 이모지 
            })
            // return Promise.reject(new Error('오렌지는 다 팔림!'))
        }
        
        // 바나나와 사과를 동시에 가지고옴
        // 순차적으로 처리 -> 총 4초가 걸림
        // 4초 후 ['🍌', '🍎'] 배열로 한번에 찍힘
        getBanana() // 1초 있다가
            .then((banana) =>
                getApple() // 3초있다가
                    .then((apple) => [banana, apple]))
                    .then(console.log) // 출력 단축형

    </script>
</body>
</html>

▲ 4초 후 결과 찍힘

 

2. all()

  • 여러 개의 Promise 객체를 동시에 실행하고, 모든 Promise 객체가 완료될 때까지 기다린 후 결과값을 배열로 반환하는 메소드
  • 배열에 포함된 Promise 객체들은 동시에 실행되며, 모든 Promise 객체가 resolve되면 , then() 메소드로 등록한 콜백 함수가 실행
  • 만약 Promise 객체 중 하나라도 reject 상태가 된다면, Promise.all() 메소드는 거부 상태가 된 Promise 객체를 반환하고, 이후의 Promise 객체들은 실행되지 않음
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise3</title>
</head>
<body>
    <h2>promise3</h2>
    <script>
        function getBanana(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍌')
                }, 1000)  // 1초후 바나나 이모지 
            })
        }

        function getApple(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍎')
                }, 3000)  // 3초후 사과 이모지 
            })
        }

        function getOrange(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍊')
                }, 4000)  // 4초후 오렌지 이모지 
            })
            // return Promise.reject(new Error('오렌지는 다 팔림!'))
        }
        
        // Promise.all 메소드
        // 3초가 걸림: 병렬적으로 한번에 모든 Promise들을 실행(1초와 3초를 동시에 실행함)
        Promise.all([getBanana(), getApple()])
            .then((fruits) => console.log('Promise.all: ', fruits))
        
    </script>
</body>
</html>

▲ 3초 뒤에 then 블록에서 작성한 결과가 출력


 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise3</title>
</head>
<body>
    <h2>promise3</h2>
    <script>
        function getBanana(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍌')
                }, 1000)  // 1초후 바나나 이모지 
            })
        }

        function getApple(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍎')
                }, 3000)  // 3초후 사과 이모지 
            })
        }

        function getOrange(){
            // return new Promise((resolve) => {
            //     setTimeout(() => {
            //         resolve('🍊')
            //     }, 4000)  // 4초후 오렌지 이모지 
            // })
            return Promise.reject(new Error('오렌지는 다 팔림!'))
        }
        
       
        // 하나라도 실패하면 전체가 실패
        Promise.all([getBanana(), getApple(), getOrange()])  
            .then((fruits) => console.log('Error: ', fruits))
            .catch(console.log)


        
      

    </script>
</body>
</html>

▲ 오렌지 함수에서 reject를 콜백으로 받았기 때문에 하나라도 거부되면 모두 실행되지 않음


3. allSettled()

  • 모든 Promise 객체가 완료될 때까지 기다리지 않고, 모든 Promise 객체의 상태가 결정될 때까지 기다린 후결과값을 배열로 반환하는 메서드
  • 열에 포함된 Promise 객체들은 동시에 실행되며, 모든 Promise 객체의 상태가 결정될 때까지 기다림
  • 모든 Promise 객체가 이행(fulfilled) 또는 거부(rejected) 상태가 되면, then() 메서드로 등록한 콜백 함수가 실행
  • 콜백 함수에는 각 Promise 객체들의 상태와 결과값이 객체의 배열로 전달
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise3</title>
</head>
<body>
    <h2>promise3</h2>
    <script>
        function getBanana(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍌')
                }, 1000)  // 1초후 바나나 이모지 
            })
        }

        function getApple(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍎')
                }, 3000)  // 3초후 사과 이모지 
            })
        }

        function getOrange(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍊')
                }, 4000)  // 4초후 오렌지 이모지 
            })
            // return Promise.reject(new Error('오렌지는 다 팔림!'))
        }
       
        
        // allSettled: 에러가 발생하더라도 모든 프로미스들의 결과를 반환
        Promise.allSettled([getBanana(), getApple(), getOrange()])
            .then((fruits) => console.log('Promise.allSettled: ', fruits))
            .catch(console.log)


    </script>
</body>
</html>

▲ fullfilled(resolve)되었고 결과값을 배열로 반환함


4. race()

  • 배열에서 가장 먼저 결정된 Promise 객체를 반환하는 메서드
  • Promise 객체 배열 중 가장 먼저 상태가 결정된 Promise 객체를 반환
  • Promise.race() 메서드가 반환한 Promise 객체는 then() 메서드로 새로운 콜백 함수를 등록할 수 있음
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise3</title>
</head>
<body>
    <h2>promise3</h2>
    <script>
        function getBanana(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍌')
                }, 1000)  // 1초후 바나나 이모지 
            })
        }

        function getApple(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍎')
                }, 3000)  // 3초후 사과 이모지 
            })
        }

        function getOrange(){
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve('🍊')
                }, 4000)  // 4초후 오렌지 이모지 
            })
            // return Promise.reject(new Error('오렌지는 다 팔림!'))
        }


        // // race: 주어진 Promise 중에서 가장 빨리 수행된 것을 출력
        Promise.race([getBanana(), getApple(), getOrange()])
            .then((fruit) => console.log('Promise.race: ', fruit))
            
    </script>
</body>
</html>

▲ 가장 먼저 상태가 결정된 Promise 객체 (바나나)가 출력

 

728x90
반응형
LIST