[DAY - 59] async / await, fetch, axios, insertAdjacentHTML, 데이터 출력 예제

2023. 5. 25. 23:48·🔥 부트캠프-웹 개발 🔥/JavaScript_advanced
  • async / await
  • fetch
  • axios
  • insertAdjacentHTML
  • 데이터 출력 예제

 

 

1) async / await

 

const test = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('1번 실행');
            resolve();
        }, 2000);
    });
};
const test1 = () => console.log('2번 실행');
console.log('시작');


const make = async () => {
    await test();
    test1();
}
make();



시작
1번 실행
2번 실행

 

async은 Promise 기반이라고 생각하면 된다. await는 async가 처리 될 때 까지 기다린 후 실행된다.

따라서 위 코드를 실행시키면 시작이 출력되고, 2초 뒤에 1번 실행, 2번 실행이 출력되게 된다.

 

 

2) fetch

 

// data1
{
    "userId" : 1, 
    "name" : "김", 
    "age" : 30,
    "addr" : "서울"
}

fetch('./data/data1.json')
.then(res=>res.json())
.then(res=>console.log(res))

fetch는 아래와 같이 작성한다.

 

fetch('파일경로', 옵션)
.then((응답완료) => 응답완료.json())
.then((json받음) => console.log(받은 json파일 출력));

 

 

html을 실행한 후 console을 확인하면 위와 같이 data1파일이 잘 불러와 진 것을 볼 수 있다.

 

 

3) axios

 

axios의 경우 아래와 같이 작성한다.

 

axios.get('url', 옵션)

.then(응답완료=>응답완료 값)

 

    <script>
        axios.get('./data/data1.json')
        .then(res=>console.log(res))
    </script>

 

여기서 data 값만 출력하고 싶으면 res의 data를 불러오면 된다.

 

    <script>
        axios.get('./data/data1.json')
        .then(res=>console.log(res.data))
    </script>

 

 

4) insertAdjacentHTML

 

html을 문서에 삽입할 때 사용하는 메서드이다.

 

// data2.html
<h1 class="text">안녕하세요 비동기처리</h1>
<h2 class="text">Ajax 소개</h2>
<h3 class="text">axios / fetch</h3>

<body>
    <button class="btn">문서 불러오기</button>
    <div class="box">
        <p>데이터 불러오기</p>
    </div>
    <script>
        const btn = document.querySelector('.btn');
        const box = document.querySelector('.box');
        btn.addEventListener('click', e => {
            const url = './data/data2.html'
            fetch(url)
                .then(res => res.text())
                .then(text => box.insertAdjacentHTML('beforeend', text))
        })
    </script>
</body>

 

 

5) 데이터 출력 예제

 

// data3.json
{
    "item" : [
        { "id" : 1, "name" : "김", "age" : 20, "addr" : "서울"},
        { "id" : 2, "name" : "이", "age" : 30, "addr" : "인천"},
        { "id" : 3, "name" : "박", "age" : 20, "addr" : "수원"},
        { "id" : 4, "name" : "최", "age" : 40, "addr" : "수원"},
        { "id" : 5, "name" : "윤", "age" : 50, "addr" : "서울"},
        { "id" : 6, "name" : "정", "age" : 10, "addr" : "서울"},
        { "id" : 7, "name" : "안", "age" : 20, "addr" : "인천"},
        { "id" : 8, "name" : "채", "age" : 30, "addr" : "시흥"},
        { "id" : 9, "name" : "고", "age" : 60, "addr" : "안산"},
        { "id" : 10, "name" : "금", "age" : 40, "addr" : "서산"}
    ]
}

<body>
    <div class="box">
        <table>
            <caption>학생명단</caption>
            <colgroup>
                <col class="w1">
                <col class="w2">
                <col class="w3">
                <col class="w4">
            </colgroup>
            <thead>
                <tr>
                    <th>번호</th>
                    <th>이름</th>
                    <th>나이</th>
                    <th>주소</th>
                </tr>
            </thead>
            <tbody class="table-tbody">
                <!-- 생성후 데이터 출력 -->
            </tbody>
        </table>
    </div>
    <script>
        const tbody = document.querySelector('.table-tbody')
        fetch('./data/data3.json')
            .then(res => res.json())
            .then(data => {
                for (let i = 0; i < data.item.length; i++) {
                    let tr = document.createElement('tr')
                    let td = document.createElement('td')
                    td.textContent = data.item[i].id
                    tr.append(td)
                    td = document.createElement('td')
                    td.textContent = data.item[i].name
                    tr.append(td)
                    td = document.createElement('td')
                    td.textContent = data.item[i].age
                    tr.append(td)
                    td = document.createElement('td')
                    td.textContent = data.item[i].addr
                    tr.append(td)
                    tbody.append(tr)
                }
            })
    </script>
</body>

 

json파일에 배열 형식으로 담은 data를 fetch를 사용해 불러왔다.

출력될 부분은 tbody이므로 tbody에 tr과 td를 생성하고 append해주었다.

 

 

<body>
    <div class="box">
        <table>
            <caption>학생명단</caption>
            <colgroup>
                <col class="w1">
                <col class="w2">
                <col class="w3">
                <col class="w4">
                <col class="w5">
            </colgroup>
            <thead>
                <tr>
                    <th>번호</th>
                    <th>이름</th>
                    <th>나이</th>
                    <th>주소</th>
                    <th>관리</th>
                </tr>
            </thead>
            <tbody class="table-tbody">
                <!-- 생성후 데이터 출력 -->
            </tbody>
        </table>
        <div class="btn">
            <button class="allDel">전체 삭제</button>
            <button class="allRe">전체 복구</button>
        </div>
    </div>
    <script>
        const tbody = document.querySelector('.table-tbody')
        const allDel = document.querySelector('.allDel')
        const allRe = document.querySelector('.allRe')
        let tableDel = document.querySelectorAll('.tableDel')
        fetch('./data/data3.json')
            .then(res => res.json())
            .then(data => {
                function make() {
                    tbody.innerHTML = ""
                    for (let i = 0; i < data.item.length; i++) {
                        let tr = document.createElement('tr')
                        let td = document.createElement('td')
                        td.textContent = data.item[i].id
                        tr.append(td)
                        td = document.createElement('td')
                        td.textContent = data.item[i].name
                        tr.append(td)
                        td = document.createElement('td')
                        td.textContent = data.item[i].age
                        tr.append(td)
                        td = document.createElement('td')
                        td.textContent = data.item[i].addr
                        tr.append(td)
                        td = document.createElement('td')
                        td.innerHTML = '<button class="tableDel">삭제</button>'
                        tr.append(td)
                        tbody.append(tr)
                        del();
                    }
                }
                function del(){
                    tableDel = document.querySelectorAll('.tableDel')
                    tableDel.forEach(del => {
                        del.addEventListener('click', e => {
                            e.target.parentElement.parentElement.remove();
                        })
                    })
                }
                allDel.addEventListener('click', e => {
                    tbody.innerHTML = ""
                })
                allRe.addEventListener('click', e => {
                    make();
                })
                make();
                del();
            })
    </script>
</body>

table에 관리 th를 하나 추가하고 innerHTML로 추가된 td에 button을 넣어주었다.

tbody에 추가하는 함수와 삭제버튼 함수를 따로 만들어 코드를 줄였다.

 

'🔥 부트캠프-웹 개발 🔥/JavaScript_advanced' 카테고리의 다른 글
  • [DAY - 63] module 사용법, import default, module 합치기, module 예제
  • [DAY - 61] API(jsonplaceholder, news, pixabay)
  • [DAY - 58] static, private, try / catch
  • [DAY - 57] class 예제 연습
Yeonhub
Yeonhub
✨ https://github.com/yeonhub 📧 lsy3237@gmail.com
  • Yeonhub
    비 전공자의 Be developer
    Yeonhub
  • 전체
    오늘
    어제
    • 전체보기 (169)
      • 🔍 Tech 🔍 (19)
        • Front-End (11)
        • Back-End (4)
        • AI (1)
        • Server (1)
        • Etc (2)
      • 💡 원티드 프리온보딩 챌린지 💡 (14)
        • PRE-ONBOARDING_AI (11월) (1)
        • PRE-ONBOARDING_FE (2월) (2)
        • PRE-ONBOARDING_FE (1월) (2)
        • PRE-ONBOARDING_FE (12월) (9)
      • 🔥 부트캠프-웹 개발 🔥 (118)
        • HTML5 (7)
        • CSS3 (21)
        • JavaScript (27)
        • JavaScript_advanced (9)
        • React (24)
        • Next (1)
        • MYSql (5)
        • Node (5)
        • 오늘하날(개인프로젝트) (12)
        • 이젠제주투어(팀프로젝트) (7)
      • 💻 CS 💻 (1)
        • 알고리즘 (1)
      • ⚡ 코딩테스트 ⚡ (11)
        • JavaScript (11)
      • 📚 Books 📚 (6)
        • 클린 아키텍처 (2)
        • 인사이드 자바스크립트 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    컴파운드 컴포넌트 패턴
    라스콘
    react native expo fcm
    expo deep linking
    javascript fcm
    react native firebase analytics
    rn bottom sheet
    rn admob
    라스콘4
    expo google map
    node fcm
    expo fcm
    node cron
    php node
    bottom sheet
    Node
    expo 길찾기
    expo fcm push
    expo node fcm
    react native bottom sheet
    python node
    react vite
    expo 지도
    react native analytics
    node crontab
    프론트엔드 테스트코드
    react native admob
    node.js fcm
    expo map
    expo admob
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 59] async / await, fetch, axios, insertAdjacentHTML, 데이터 출력 예제
상단으로

티스토리툴바