JS/JS 수업분

[JS] day13_async_promiseChain 데이터 가져오기 2

congs 2023. 4. 20. 23:50
 
 
<!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>Promise Chain 방식</title>
</head>
<body>
    <button type="button" id="btn">데이터 가져오기</button>
    <ul id="ul"></ul>
    <script>
       
        document.getElementById('btn').addEventListener('click',()=>{
            // fetch('https://jsonplaceholder.typicode.com/todos/1') //데이터 가져와서
            // .then(resp => resp.json()) //1. 매개변수 resp에 json형식으로 데이터를 넣고 리턴
            // .then(json => console.log(json)); //콘솔에 찍어라
            // .catch(err=> console.log(err)); //실패시
           
           
            // .then(resp => resp.text()) //2. 매개변수 resp에 text형식으로 데이터를 넣고 리턴
            // .then(text => console.log(text)); //콘솔에 찍어라
           
           
            //받아온 json객체를 화면에 li로 출력해보기
            .then(resp => resp.json())
            .then(json => printData(json)) //성공시
            .catch(err=> console.log(err)); //실패시
           
        })
       
       
        //화면에 li로 출력하는 함수
        let str=" ";
        function printData(object){ // object = json객체
            for(const o in object){
                str += `<li>${o}:${object[o]}</li>`;
            }
            document.getElementById('ul').innerHTML = str;
        }
    </script>
   
    <!-- <script>
        // 1~5번 데이터까지 화면에 출력
        document.getElementById('btn').addEventListener('click',()=>{
           
            //1번 데이터
            for(let i=1; i<=5; i++) {
                fetch(`https://jsonplaceholder.typicode.com/todos/${i}`)
                .then(resp => resp.json())
                .then(json => printData(json));
            }
           
           
        })
       
        let str1="";
       
        //화면에 li로 출력하는 함수
        function printData(object){ // object = json객체
            for(const o in object){
                str1 += `<li>${o}:${object[o]}</li>`;
            }
            document.getElementById('ul').innerHTML = str1;
        }
    </script> -->
</body>
</html>