비전공자 코딩 배우기 _9, 10주차 자바스크립트 동기와 비동기

Jinny·2021년 7월 17일
0

TIL

목록 보기
7/28
post-thumbnail

👏🏻 동기와 비동기

동기 : 요청을 보낸 후 해당 요청의 응답을 받아야 다음 동작을 실행하는 방식

비동기 : 요청을 보낸 후 응답과 관계 없이 다음 동작을 실행하는 방식

자바스크립트는 동기적이다. 호이스팅이 된 이후부터 우리가 작성한 순서대로 동기적으로 진행된다.

console.log('1');
setTimeout(() => {
	console.log('2');
}, 1000);
console.log('3');

을 예제로 들어보면, 1 → 3 → 2 순서대로 비동기적으로 실행이 된다.

setTimeout과 같은 함수를 콜백 함수라고 한다.

👆🏻 Synchronous callback

function printImeediately(print) {
	print();
}
printImmediately(()=> console.log('hello'));

위의 예제를 추가하면 1 → 3 → hello → 2 순서대로 실행이 된다.

✌🏻 Asynchronous callback

function printWithDelay(print, timeout) {
	setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'), 2000);

위의 예제를 추가하면 1 → 3 → hello → 2 → async callback 순서대로 실행이 된다.

정리를 해보면

function printImmediately(print) {
	print();
}

function printWithDelay(print, timeout) {
	setTimeout(Print, timeout);
}

console.log('1'); // 동기
setTimeout(()=>console.log('2'), 1000) // 비동기
console.log('3'); // 동기
printImmediately(()=>console.log('hello')); // 동기
printWithDelay(()=>consoele.log('async callback'), 2000); // 비동기

으로 실행된다고 이해하면 된다.


👿 콜백 지옥 예제

class UserStorage {
	loginUser(id, password, onSuccess, onError) {
		setTimeout(()=>{
		if (
			(id === 'ellie' && password === 'dream') ||
			(id === 'coder' && password === 'academy')
		) {
			onSuccess(id);
		} else {
			onError(new Error('not found'));
		}
		}, 2000);
	}

	getRoles(user, onSuccess, onError) {
		setTimeout(()=> {
			if(user === 'ellie') {
				onSuccess({ name: 'ellie', role: 'admin' });
			} else {
				onError(new Error('no access'));
			}
		}, 1000);
	}
}

const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(id, password, (user) => {
	userStorage.getRoles(user, (userWithRole) => {
		alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
		);
	}, (error) => {
		console.log(error})
	}, (error) => {
		console.log(error)}
);

🔓 콜백 지옥의 문제점

  1. 가독성이 떨어진다.
  2. 에러가 발생하거나 디버깅을 해야하는 경우에도 문제를 찾기 힘들다.
  3. 유지보수가 어렵다.

💜 출처 : 드림코딩 by 엘리 https://www.youtube.com/watch?v=s1vpVCrT8f4&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=11 💜


profile
코린이

0개의 댓글