[JavaScript] 기초반 강의 헷갈렸던 부분 정리

MOON HEE·2022년 6월 15일
0

제주코딩베이스캠프 호준님의 자스 기초반 강의가 마무리되었다.
마지막 강의에서 예외처리, 전개표현 등 잘 몰랐던 개념들을 정리할 수 있어서 좋았다.
블로그에 정리해놓고 필요할 때 찾아보기 위해 남긴다!

1. 예외처리

try하다가 에러가 나면 catch에서 잡게 된다.
catch(e)의 'e'는 error를 의미하는데, 이때 console.log(e)를 찍어보면 어떤 에러인지 알 수 있다.
finally는 에러가 나든 안나든 무조건 실행된다.

try {
	// code
} catch(e) {
	// code
} finally {
	// code
}

//throw new Error(message);
//throw new SyntaxError(message);
//throw new ReferenceError(message);

2. 전개표현식

let arr1 = [1, 2, 3, 4];
let arr2 = [10, 20, 30, 40];
let arr3 = [100, ...arr1, 200, ...arr2, 300];

console.log(arr3) // [100, 1, 2, 3, 4, 200, 10, 20, 30, 40, 300]
Math.max(...arr3) // 300

let [a, b, c, ...d] = [10, 20, 30, 40, 50, 60, 70]
console.log(a) // 10
console.log(b) // 20
console.log(c) // 30
console.log(d) // [40, 50, 60, 70]

3. 구조분해할당

for (let [[i, j], k] of [[[1, 2], 2], [[1, 2], 4]]) {
    console.log(i, j); // 1 2    1 2
}

4. 동기와 비동기

// 순서대로 한다면 덧셈, 곱셈, hello world 순이지만
// 비동기이기 때문에 hello world, 곱셈, 덧셈 순이 됨
function 덧셈(a, b, 콜백함수) {
    setTimeout(()=>{
        let result = a + b
        console.log(result)
    }, 2000)
}
function 곱셈(a, b, 콜백함수) {
    setTimeout(()=>{
        let result = a * b
        console.log(result)
    }, 1000)
}

덧셈(20, 30)
곱셈(2, 6)
console.log('hello world')

5. Promise

new Promise((resolve, reject) => {
        //code
    })
    .then(result => result)
    .then(result => result)
    .catch(err => err)
    .finally(result => result)


let p = new Promise(function(resolve, reject) {
    resolve('hello world'); // 아래 reject 주석 후 실행해보기(아래 사진처럼 로직이 실행됨), then을 따라감
    reject('hello world'); // 위 resolve 주석 후 실행해보기, catch를 따라감
}).then(메시지 => {
    alert(메시지);
    return 메시지.split(' ')[0]
}).then(메시지 => {
    alert(메시지);
    return 메시지[0]
}).then(메시지 => {
    alert(메시지);
}).catch(메시지 => {
    alert('catch 실행!! :' + 메시지);
  	throw new Error('에러야!!');
}).catch(메시지 => {
    alert('catch 실행!! :' + 메시지);
});


fetch도 Promise다.

const f = fetch('https://raw.githubusercontent.com/paullabkorea/coronaVaccinationStatus/main/data/data.json')
    .then(data => {
    	console.log('데이터 받기 성공!')
      	const jsonData = data.json()
        return jsonData
    })
	.then(json => {
    	json.forEach(item => {
        	console.log(item)
        })
    })
	.catch(e => {
    	console.log('json 변환 실패!!')
    })

fetch는 데이터를 가져올 때도 사용할 수 있다.

// Promise 패턴
function get() {
	fetch('url 기입', {
    	method: "GET",
    })
  	.then(response => response.json())
  	.then(json => console.log(json))
}

get()

  • fetch는 데이터를 보낼 때도 사용할 수 있다.
  • async, await을 사용하는 이유 : 비동기를 동기처럼(= 기다렸다가) 사용하고 싶기 때문이다.
profile
자고 일어나면 해결되는게 더 많은 듯 그럼 잘까

0개의 댓글