Javascript 기초 3

금송·2024년 8월 17일
0

이론

목록 보기
8/17
post-thumbnail

this

function person(name) {
    this.name = name;
    console.log(this)
}

const persontest = Person // 함수
const persontest = Person('licat')

/////////////////////////////////////

function Person(name) {
this.name = name;
console.log(this);
// return this
}

// new 의 역할 - 함수에서 새로운 this를 만들어줌
// 생산품 = 설계도면
const person1 = new Person('licat');
// Person { name: "licat" }
const person2 = new Person('mura');
// Person { name: "mura" }

var로 변수 선언하면 윈도우에 저장됨

호출 위치에 따른 this

함수 - 윈도우

이벤트 핸들러 - 이벤트를 발생시킨 DOM or 요소

객체 - 객체 자기 자신

<head>
    <title>이벤트 핸들러 내에 this</title>
</head>
<body>
<button id="btn">Hello World!</button>
<script>
    // 해당 방법으로 쓰기도 함
    // function $(el) {
    //     return document.querySelector(el);
    // }
    // const button = $('#btn')

    const button = document.getElementById('btn');
    button.addEventListener('click', function () {
        console.log(this); // <button id="btn">Click me!</button>
    })
    // 이벤트에서 가르키는 DOM요소 = this
</script>
</body>

//////////////////////////////////////////

<body>
<input type="checkbox" id="checkbox" /> 체크해보세요.

<script>
    const checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', function () {
        // this의 활용도 확인
        if (this.checked) {
            document.body.style.backgroundColor = 'lightblue';
        } else {
            document.body.style.backgroundColor = '';
        }
    });
</script>
</body>

this는 중급자 넘어가기 전에 한번 더 정리

call(), apply(), bind() 메서드를 사용하여 this의 값을 명시적으로 설정할 수 있는 방법도 찾아보기

반목문

for in - key값 순회

for of - 객체의 값 순회

object - iterable이 아니기 때문에 for of가 불가

//in 다른 언어 > value , 자바스크립트 > key를 확인하는 용도
//for...of 문 익스플로러에서 사용 불가, for...in 문 익스플로러에서 사용 가능
// 포털서비스 - 모토롤라까지 지원함.. .1%도 무시할 수 없음.. 지원하지않는 문법은 지양.. / 익스플로러를 버릴려면 버려도 괜찮음
const arr = [10, 20, 30, 40, 50]
const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}

for (let key in obj) {
    console.log(key, obj[key]);
}

for (let key in arr) {
    console.log(key, arr[key]);
}

// for (let valule of obj) {
//     console.log(key, obj[key]);
// }

for (let value of arr) {
    console.log(value);
}

for (let value of Object.values(obj)) {
    console.log(value);
}

let data = [
    {
        "지역이름": "전국",
        "확진자수": 24889,
        "격리해제수": 23030,
        "사망자수": 438,
        "십만명당발생율": 48.0,
        "지역별확진자비율": ""
    },
    {
        "지역이름": "서울",
        "확진자수": 5607,
        "격리해제수": 5050,
        "사망자수": 66,
        "십만명당발생율": 57.61,
        "지역별확진자비율": 22.53
    },
    {
        "지역이름": "부산",
        "확진자수": 491,
        "격리해제수": 423,
        "사망자수": 4,
        "십만명당발생율": 14.39,
        "지역별확진자비율": 1.97
    },
    {
        "지역이름": "대구",
        "확진자수": 7141,
        "격리해제수": 6933,
        "사망자수": 196,
        "십만명당발생율": 293.09,
        "지역별확진자비율": 28.69
    }
];

for (let d of data) {
    console.log(d['지역이름'], d['확진자수'], d['격리해제수'], d['사망자수'], d['십만명당발생율'], d['지역별확진자비율']);
}

for (let i = 0; i < data.length; i++) {
    console.log(data[i]['지역이름'], data[i]['확진자수'], data[i]['격리해제수'], data[i]['사망자수'], data[i]['십만명당발생율'], data[i]['지역별확진자비율']);
}

// 내용 잘 이해해두기
// for in 은 key 값을 순환 (배열에선 인덱스)
// for of 는 value 값을 순환
// object는 무엇이 안되는지? iterable이 아니기 때문에 for of가 안됨 (for value of Object.Values(obj) 는 됨

map

key, value로 이루어진 데이터를 저장할 때 사용

ES6에 추가된 문법

// key,value로 이루어진 데이터를 저장할 때 사용, EC6에 추가된 문법
// 어떠한 언어도 이렇게 비슷한 자료형을 가지고 있는 경우는 없습니다.
// let m = new Map();
// console.log(m); // Map(0) {}

let m = new Map();

m.set('하나', '1');
m.set(1, '하나');
m.set(true, 1);
m.set(false, 0);

console.log(m);
console.log(m.get('하나')); // '1'
console.log(m.get(true)); // 1

// 값이 있는지 확인하는 법
// in 연산자
// map에서는 in이 생각대로 작동하지 않을수있으니 has 메서드를 활용 delete는 값 제거 메서드 size는 크기 확인 메서드
console.log('하나' in {'하나':'1', '둘':'2'}) // true

console.log(m.has('하나')); // true
console.log(m.delete('하나')); // true
console.log(m.size); // 2

// 메서드를 옆으로 늘여 쓰는것 : 메서드 체이닝
const data = new Map().set('name', 'licat').set('age', 10).set('height', 180);

for (const value of data) {
    console.log(value[0]);
    console.log(value[1]);
}

for (const [key, value] of data) {
    console.log(key);
    console.log(value);
}

console.log([...data.keys()]);
console.log([...data.values()]);

// 배열을 Map으로 변환
let temp = new Map([
    [1, 10],
    [2, 20],
    [3, 30],
    [4, 40],
]);

// 객체를 Map으로 변환
let temp2 = new Map(Object.entries({ one: 1, two: 2 }));

set

// 중복을 허락하지 않는 자료형
// 중복하지 않는 데이터를 저장할 때 사용
// 중복을 제거하는 용도로도 사용

let s = new Set();
// console.log(s); // Set(0) {}

s.add(10);
s.add(20);
s.add(30);
s.add(30); // 중복된 값은 추가되지 않음
s.add(30);
s.add(30);

console.log(s); // Set(3) {10, 20, 30}

let ss = new Set('abcdeeeeeeeee');
console.log(ss);
console.log(ss.size);

let sss = new Set([10, 20, 30, 10, 20, 30, 30]);
console.log(sss);
console.log(sss.size);
console.log(sss.has(10));

console.log(sss.delete(10));
console.log(sss.has(10));

let s2 = new Set(['apple', 'banana', 'orange']);

for (let value of s2) {
  console.log(value);
}

let setA = new Set(['apple', 'banana', 'orange']);
let setB = new Set(['banana', 'kiwi', 'orange']);

// 교집합
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Set(2) {"banana", "orange"}

// 합집합
let union = new Set([...setA, ...setB]);
console.log(union); // Set(4) {"apple", "banana", "orange", "kiwi"}

// 차집합
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Set(1) {"apple"}

////////////////////////////////////////////

// array에 filter와 reduce
// filter는 안에 들어간 함수가 true를 리턴하는 요소만 모아서 새로운 배열을 만든다
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.filter(x => x % 2 === 0 && x > 5)

// reduce는 배열의 각 요소를 연산
let arr2 = [1, 2, 3, 4, 5];
arr2.reduce((a, c) => a + c); // a는 누적값(accumulator), c는 현재(current value)
// 0이 없으면 비어있는 배열일때 에러가 남

JSON

JavaScript Object Notation

// 주로 통신에서 많이 사용됨. 가벼운 텍스트를 교환하는데 사용. 이미지는 전송 x
// 브라우저가 해석할 수 있는 자료형이 자바스크립트였어서
// 쌍따옴표에 넣고 마지막엔 콤마가 없어야 한다.
// 항상 중괄호로 시작하는 것은 아니고 대괄호나 중괄호로 시작할 수 있다.
// 대괄호의 사용 이유는 바로 순환을 쓰기위해
const data = {
  "name": "licat",
  "age": 25,
  "hobby": ["낚시", "독서", "등산", "요리"],
  "relationship": {
    "friend": ["뮤라", "빙키", "개리"],
    "enemy": ["라이언"]
  }
}

console.log(data["hobby"][0]); //낚시

// JSON
// {
//   "squadName": "슈퍼히어로",
//         "members": [
//   {
//     "name": "아이언맨",
//     "age": 29,
//     "본명": "토니 스타크"
//   },
//   {
//     "name": "헐크",
//     "age": 39,
//     "본명": "부르스 배너"
//   }
// ]
// }

// XML (RSS - XML의 데이터를 전송하는 방식) 계층적으로 표현하는데 용이
// <?xml version="1.0" encoding="UTF-8" ?>
// <root>
// <squadName>슈퍼히어로</squadName>
// <members>
//   <name>아이언맨</name>
//   <age>29</age>
//   <본명>토니 스타크</본명>
// </members>
// <members>
//   <name>헐크</name>
//   <age>39</age>
//   <본명>부르스 배너</본명>
// </members>
// </root>

// JSON.parse
// 서버에서 받은 데이터를 객체(object, array)로 변환할때 사용

const json = '{"result":true, "count":42}';
console.log(json[0])

const obj = JSON.parse(json);
console.log(obj); // 문자열에서 객체로 변환
console.log(obj['result'])

const json2 = '[10, 20, 30]';
console.log(json2[0])

const obj2 = JSON.parse(json2);
console.log(obj2); // 문자열에서 객체로 변환
console.log(obj2[0])

// JSON.stringify
// 객체(object, array)를 문자열로 반환
// 내가 작성한 데이터를 서버로 전송할 때 사용

const obj3 = { result: true, count: 42 };
const obj4 = { result: [10, 20, 30], count: 42 };
const json3 = JSON.stringify(obj3);
const json4 = String(obj4);
const json4_ = JSON.stringify(obj4);

console.log(json3);
console.log(json4);
console.log(json4_);

console.log(json3[0]); // 객체에서 문자열로 변환
console.log(json3[1]);

DOM 트리에 접근하기 1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<!--    <title>DOM</title>-->
    <title>My Document</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
<script>
    //DOM
    //Document Object Model
    // Html문서의 내용을 트리 형태로 구조화 해서 웹페이지와 프로그래밍 언어를 연결시켜주는 역할
    document
    // #document (file:///C:/Users/paullab/Desktop/%EC%98%A4%EB%A5%B4%EB%AF%B8%20BE%206/048.html)
    document.all
    // HTMLAllCollection(6) [html, head, title, body, h1, p]
    document['head']
    // <head>…</head>
    document.head
    // <head>…</head><title>My Document</title></head>
    document.head.childNodes
    // NodeList(3) [text, title, text]0: text1: title2: textlength: 3[[Prototype]]: NodeList
    document.head.childNodes[1]
    // <title>My Document</title>
    document.head.childNodes[1].innerText
    // 'My Document'
    document.head.childNodes[1].innerText = 'hello world'
    // 'hello world'
    document.body.childNodes[1]
    // <h1>Hello, World!</h1>
    document.body.childNodes[1].innerText
    // 'Hello, World!'
    document.body.childNodes[1].innerText = 'licat'
    // 'licat'
</script>
</body>
</html>

DOM 트리에 접근하기 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM 트리에 접근하기</title>
</head>
<body>
<h1 id="logo" class="title">Hello world</h1>
<section>
    <!-- 네이밍을 스네이크로 하는 이유는 클릭했을때 해당 단어만 잡기 편하기 위해 -->
    <h2 id="section-title">HTML 1</h2>
    <p id="contents">HTML is HyperText Markup Language 1</p>
</section>
<section>
    <!-- 네이밍을 스네이크로 하는 이유는 클릭했을때 해당 단어만 잡기 편하기 위해 -->
    <h2 id="section-title">HTML 1</h2>
    <p id="contents">HTML is HyperText Markup Language 1</p>
</section>
<p class="hello">hello world</p>
<script>
    const logo = document.getElementById('logo')
    // document.getElementById('logo')
    // document.getElementById('logo')
    const sectionTitle = document.querySelector('#section-title');
    const sectionTitleAll = document.querySelectorAll('#section-title');
    const hello = document.querySelector('.hello');

    console.log(logo);
    console.log(sectionTitle);
    console.log(sectionTitleAll);
    console.log(hello);
</script>
</body>
</html>

DOM 제어하기 1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM 제어하기</title>
<style>
    .blue {
        background-color: blue;
        color: white;
    }
</style>
</head>
<body>
<button class="hello">HELLO!</button>
<script>
    // 앞에서는 Text만 수정했었지만
    // 이벤트 추가, 클래스 제어, 요소 생성 및 삭제, 속성 제어 등 다양한 DOM 제어를 해볼 예정
    const myBtn = document.querySelector('button')

    // 1. 이벤트 추가
    // myBtn.addEventListener('click', () => {
    //     console.log('hello world')
    // })
    // 2. 클래스 제어
    myBtn.addEventListener('click', function () {
        // myBtn.classList.add("blue"); // 클래스를 추가합니다.
        // myBtn.classList.remove("blue"); // 클래스를 제거합니다.
        myBtn.classList.toggle('blue'); // 클래스를 토글합니다. 있으면 두고 없으면 추가해줌
        console.log(myBtn.classList.contains('blue')); // 클래스가 있는지 확인합니다.
    });

    // 3. 요소 제어
    const data = {
        title: 'hello',
        content: 'world',
        price: 3000
    }
    const section = document.createElement('section');
    const name = document.createElement('h2');
    const content = document.createElement('p');
    const price = document.createElement('p');
    const img = document.createElement('img')

    // img.setAttribute('src', 'https://via.placeholder.com/300'); // 무작위 이미지
    img.src = 'https://via.placeholder.com/300';
    name.textContent = data.name;
    content.textContent = data.content;
    price.textContent = data.price;

    section.appendChild(img);
    section.appendChild(name);
    section.appendChild(content);
    section.appendChild(price);

    // document.body.appendChild(section)
    document.body.append(section) //appendChild 와 다른점은 노드 뿐만 아니라 여러개의 노드를 한번에, 그리고 텍스트도 자식 노드로 포함시킬 수 있다는것 입니다.

    // 3-1 속성 제어
    price.style.color = 'red';
    // font-size -> fontSize
    price.style.fontSize = '20px';

    // 서드파티쿠키 - 페이지에서 광고가 나오는 이유, 제 3자에서 제공하는 쿠키
</script>
</body>
</html>

DOM 제어하기 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM 제어하기 2/ 프론트st</title>
</head>
<body>
<script>

    //https://test.api.weniv.co.kr/mall
    const data = {
        name: 'hello',
        content: 'world',
        src: 'https://via.placeholder.com/300',
        price: 3000
    };

    document.body.innerHTML = `
    <section>
        <img src="${data.src}" alt="이미지">
        <h2>${data.name}</h2>
        <p>${data.content}</p>
        <p>${data.price}</p>
    </section>
`;

    // 1번과 비교했을 때
    // 1. 가독성이 높아졌습니다.
    // 2. 코드작성의 난이도가 낮아졌습니다.
    // 3. 요소를 컨트롤 하는 것은 1번이 더 좋습니다.
    // 4. 재활용성도 1번이 더 좋습니다.
    // 5. 이렇게 생산된 노드는 이벤트 같은 것을 가지고 있지 않습니다. 나중에 별도로 추가해야 합니다.
</script>
</body>
</html>
  • JSON 데이터 활용 예제 (방법 1)
    <!DOCTYPE html>
    <html lang="ko">
    <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>JSON 데이터 활용 예제</title>
        <style>
            main {
                display: flex;
                flex-wrap: wrap;
                gap: 20px;
            }
            section {
                width: 300px;
                border: 1px solid #333;
                border-radius: 10px;
                padding: 10px;
            }
            img {
                width: 100%;
                height: 200px;
                object-fit: cover;
                border-radius: 10px;
            }
            h2 {
                font-size: 1.5rem;
                margin: 10px 0;
            }
            p {
                font-size: 1.2rem;
                margin: 10px 0;
            }
        </style>
    </head>
    <body>
    <header>
        <h1>쇼핑몰</h1>
    </header>
    <main></main>
    <footer>
        ()위니브 대표: 이호준
    </footer>
    
    <script>
        fetch('https://test.api.weniv.co.kr/mall/')
            .then(res => res.json())
            .then(data => {
                const body = document.body;
                const main = document.querySelector('main');
                data.forEach(item => {
                    const section = document.createElement('section');
                    const img = document.createElement('img');
                    const h2 = document.createElement('h2');
                    const p = document.createElement('p');
    
                    img.src = 'https://test.api.weniv.co.kr/' + item.thumbnailImg;
                    img.alt = item.productName;
                    h2.textContent = item.productName;
                    p.textContent = item.price;
    
                    section.appendChild(img);
                    section.appendChild(h2);
                    section.appendChild(p);
    
                    main.appendChild(section);
                })
            });
    </script>
    </body>
    </html>
  • JSON 데이터 활용 예제 (방법 2)
    <!DOCTYPE html>
    <html lang="ko">
    <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>JSON 데이터 활용 예제</title>
      <style>
        main {
          display: flex;
          flex-wrap: wrap;
          gap: 20px;
        }
        section {
          width: 300px;
          border: 1px solid #333;
          border-radius: 10px;
          padding: 10px;
        }
        img {
          width: 100%;
          height: 200px;
          object-fit: cover;
          border-radius: 10px;
        }
        h2 {
          font-size: 1.5rem;
          margin: 10px 0;
        }
        p {
          font-size: 1.2rem;
          margin: 10px 0;
        }
      </style>
    </head>
    <body>
    <header>
      <h1>쇼핑몰</h1>
    </header>
    <main></main>
    <footer>()위니브 대표: 이호준</footer>
    <script>
      fetch('https://test.api.weniv.co.kr/mall/')
              .then(res => res.json())
              .then(data => {
                const main = document.querySelector('main');
                data.forEach(item => {
                  const section = `
                <section>
                    <img src="https://test.api.weniv.co.kr/${item.thumbnailImg}" alt="${item.productName}">
                    <h2>${item.productName}</h2>
                    <p>${item.price}</p>
                </section>
            `;
    
                  main.innerHTML += section;
                })
              });
    </script>
    </body>
    </html>

DOM 이벤트 흐름

브라우저가 이벤트 대상을 찾아갈 때 가장 상위의 window 객체부터 document, body 순으로 DOM 트리를 따라 내려가는 것을 캡쳐링 단계

이벤트 대상을 찾고 캡처링이 끝나면 DOM 트리를 따라 올라가며 만나는 모든 버블링 이벤트 리스터를 실행하는 것을 버블링 단계

이러한 과정에서 이벤트 리스너가 차례로 실행되는 것을 이벤트 전파

<article class="parent">
  <button class="btn" type="button">버튼</button>
</article>

<script>
  const parent = document.querySelector('.parent');
  const btnFirst = document.querySelector('.btn');

  btnFirst.addEventListener('click', (event) => {
      console.log('btn capture!');
  });

  window.addEventListener('click',() => {
      console.log('window capture!');
  },true,); // true : 캡처링 단계의 이벤트가 발생하도록 합니다.

  document.addEventListener('click',() => {
      console.log('document capture!');
  },true,);

  parent.addEventListener('click', () => {
      console.log('parent capture!');
  }, true,);

  btnFirst.addEventListener('click', (event) => {
      console.log('btn bubble!');
      // event.preventDefault(); // 브라우저의 기본 동작을 막음
      event.stopPropagation(); // 이벤트의 전파를 막음
  });

  parent.addEventListener('click', () => {
      console.log('parent bubble!');
  });

  document.addEventListener('click', () => {
      console.log('document bubble!');
  });

  window.addEventListener('click', () => {
      console.log('window bubble!');
  });
</script>

브라우저의 기본 동작을 막는 메서드

<body>
<!-- 앵커의 기본 동작을 중지 -->
<a href="https://www.naver.com" class="link">네이버 링크입니다만..</a>
<!-- submit 의 기본 동작을 중지 -->
<form action="">
    <button type="submit" class="submit">제출</button>
</form>
<script>
    const link = document.querySelector('.link');
    link.addEventListener('click', (event) => {
        console.log('clicked');
        event.preventDefault(); // 클릭은 되지만 링크 이동이 되지않음
    });
    const submit = document.querySelector('.submit');
    submit.addEventListener('click', (event) => {
        console.log('clicked');
        event.preventDefault();// 클릭은 되지만 제출이 되지않음
    });
</script>
</body>

클래스, 인스턴스

클래스 - 일종의 설계 도면 또는 템플릿

인스턴스 - 생산된 생산품

내부적인 동작은 동일하지만 더 보기 좋고 편리하게 개선된 문법 - 슈가 신텍스

// 클래스 : 일종의 설계 도면 또는 템플릿
// 인스턴스 : 설계 도면을 통해 생산된 생산품

// ES6부터 도입된 class를 사용한 방식
class Robot {
    constructor(name, year) {
        // 생성자 함수라고 합니다. 하나의 클래스는 하나의 생성자만 정의할 수 있습니다.
        // 생성자 함수는 new 키워드가 호출될 때 자동으로 실행됩니다.
        this.name = name;
        this.hp = 100;
        this.year = year;
    }

    sayYourName() {
        // 메소드를 정의합니다. 메소드는 클래스가 생성한 인스턴스를 통해 사용할 수 있습니다.
        console.log(`삐리비리. 제 이름은 ${this.name}입니다. 주인님.`);
    }
}

// 클래스를 통해 인스턴스를 생성합니다. 여기서 bot 이 인스턴스
const bot = new Robot('mura', 2024);
bot.sayYourName(); // 삐리비리. 제 이름은 mura입니다. 주인님.
bot.name
bot.hp
bot.year

//////////////////////////////////////////////////

class Robot {
  #password;

  constructor(name, pw) {
      this.name = name;
      this.#password = pw;
  }

  sayYourName() {
      console.log(`삐리비리. 제 이름은 ${this.name}입니다. 주인님.`);
  }

  get password() {
      console.log('get password 호출')
      return this.#password; // 비공개 프로퍼티로 숨김처리
  }

  set password(pw) {
      console.log('set password 호출')
      this.#password = pw;
  }
}

// get과 set사용
const bot = new Robot('재현', 1234);

console.log(bot.name) //재현
console.log(bot.password); // 1234
bot.password = 5678; // = bot.password(5678) set password 호출
console.log(bot.password); // 5678

동기와 비동기

동기 - 순차적으로 처리되는 방식

  1. (10시) licat : 로봇 청소기를 돌립니다.
  2. (11시) licat : 빨래를 합니다.
  3. (12시) licat : 설거지를 합니다.
  4. (01시) licat : 요리를 합니다.

비동기 - 순차적으로 처리되지 않는 방식

  1. (10시) licat : 로봇 청소기를 돌리면서
  2. (10시) licat : 빨래를 합니다.
  3. (10시) licat : 설거지를 합니다.
  4. (10시) licat : 요리를 하려고 물도 끓입니다.
console.log('hello')
let p = new Promise((resolve, reject) => {
    resolve('hello world'); // 성공
    // reject('hello world'); // 실패
})
.then((메시지) => {
    alert(메시지);
    return 메시지.split(' ')[0];
})
.then((메시지) => {
    alert(메시지);
    return 메시지[0];
})
.then((메시지) => {
    alert(메시지);
})
.catch((메시지) => {
    alert('catch 실행!! :' + 메시지);
});
console.log('world')
  • API 실습 CRUD(Create Read Update Delete)
    // 이 API는 30분마다 갱신되는 API
    // 중간에 초기화 되더라도 놀라지 x
    // 서버 공격 하지 x
    // CRUD Create Read Update Delete
    
    // fetch("https://eduapi.weniv.co.kr/777/blog") 전체 보기 Read
    fetch("https://eduapi.weniv.co.kr/777/blog/1") // 0번째 게시물
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((error) => console.error(error));
    
    // 게시글 작성 Create
    fetch("https://eduapi.weniv.co.kr/777/blog", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            title: "test 777",
            content: "test 777",
        }),
    })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((error) => console.error(error));
    
    // 게시글 수정 Update
    fetch("https://eduapi.weniv.co.kr/777/blog/1", {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            title: "test put !",
            content: "test put !",
        }),
    })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((error) => console.error(error));
    
    //게시글 삭제 Delete
    fetch("https://eduapi.weniv.co.kr/777/blog/1", {
        method: "DELETE",
    })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((error) => console.error(error));

async, await(에이씽크, 어웨잇)

비동기 코드를 작성하는 새로운 방법

기존의 비동기 처리 방식인 콜백이나 프로미스와는 다르게, 동기 코드처럼 보이게 작성할 수 있어 더 읽기 쉽고 이해하기 쉬움

함수 앞에 async 키워드를 붙이면 해당 함수는 항상 프로미스를 반환

함수 내부에서 await 키워드를 사용하면, 프로미스가 처리될 때까지 함수 실행을 일시 중지시키고, 결과 값을 반환

비동기 코드를 동기 코드처럼 작성할 수 있어 가독성과 유지보수성 향상

에러 처리도 일반 try/catch문을 사용할 수 있어 더 간편

/* async, await */

console.log('hello');
async function getData() {
    const response = await fetch(`https://test.api.weniv.co.kr/mall`);
    const productData = await response.json();
    console.log(productData);
}
getData();
console.log('world');
profile
goldsong

0개의 댓글