본문 바로가기
Web/JavaScript

[JavaScript] Promise객체 - 2️⃣ promise 콜백함수 축약형으로 작성하기!

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>promise2</title>
</head>
<body>
    <h2>promise2</h2>
    <script>
        function fetchEgg(chicken){
            //.resolve(): 성공시
            return Promise.resolve(`${chicken} => 🥚`)
        } 

        function fryEgg(egg){
            return Promise.resolve(`${egg} => 🍳`)
        }

        function getChicken(){
            return Promise.resolve(`🐤 => 🐓`)
            // return Promise.reject(new Error('치킨집 망함!'))
        }

        getChicken()
        // .catch(() => '🐥') // 에러가 발생했다면
        // 에러발생하고 catch찍고 then으로 내려감
        // 성공했다면 chicken 객체를 그대로 가져와서
        .then((chicken) => {
            return fetchEgg(chicken)
        })
        .then((egg) => fryEgg(egg))
        // .then: fryEgg(egg)의 결과값을 리턴
        .then((friedEgg) => console.log(friedEgg))
        .catch((error) => console.log(error.name))

        
        // 축약형 작성
        getChicken()
        .then(fetchEgg)  // 함수 이름만 적어도 됨, 매개변수는 return값으로 자동으로 들어감
        .then(fryEgg)
        .then(console.log)
        .catch(() => '🐥')
    </script>
</body>
</html>

 

728x90
반응형
LIST