반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- node
- 드림코딩
- dml
- 습윤밴드
- 크로스핏
- 메디패치
- MySQL
- 달리기
- 독서 리뷰
- 박스점프
- express
- Udemy
- Til
- 위코드
- git
- 운동일지
- nodejs
- wecode
- node.js
- SQL
- 홈트
- code kata
- github
- axios
- 러닝
- 활동 킬로칼로리
- JavaScript
- 걷기
- 월별 운동일지
- dql
Archives
- Today
- Total
RISK IT
[TIL17_23.1.25.] callback 함수 with 동기&비동기 (드림코딩 강의) 본문
반응형
콜백
자바스크립트는 동기적((synchronous)
이다.
- 호이스팅이 된 이후부터 코드 작성 순서에 맞춰 하나하나 동기적으로 처리 한다는 뜻
- 호이스팅: 변수 선언, 함수 선언 등이 제일 위로 올라가서 처리되는 것
예시
✍️ 입력
console.log('1');
console.log('2');
console.log('3');
💻 출력
1
2
3
비동기(asynchronous)
는 언제 코드가 실행될 지 예측할 수 없는 것
예시
✍️ 입력
console.log('1');
setTimeout(function () {
console.log('2');
}, 1000);
console.log('3');
💻 출력
1
3
2 // 1초 후에 콘솔에 출력
콜백함수
setTimeout(function () {
console.log('2');
}, 1000);
setTimeout()
안에 있는 function () { console.log('2')}
는 바로 실행되지 않고 parameter로 전달되어 지정한 시간 후에 다시 불러와 실행시킨다. 이것을 콜백함수
라고 한다.
setTimeout(() => console.log('2'), 1000);
// 위와 같은 함수를 arrow function으로 간단하게 표현
동기적, 비동기적 콜백함수
콜백함수도 동기적, 비동기적인 콜백으로 나뉘어진다.
Synchronous callback 예시
✍️ 입력
console.log('1');
setTimeout(function () {
console.log('2');
}, 1000);
console.log('3');
// Synchronous callback
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'));
💻 출력
1
3
hello
2 // 1초 후에 콘솔에 출력
Asynchronous callback 예시
✍️ 입력
console.log('1');
setTimeout(function () {
console.log('2');
}, 1000);
console.log('3');
// Synchronous callback
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'));
// Asynchronous callback
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
💻 출력
1
3
hello
2 // 1초 후에 콘솔에 출력
async callback // 2초 후에 콘솔에 출력
Callback 지옥 예시
✍️ 입력
class UserStorage {
// UserStorage 클래스 생성
loginUser(id, password, onSuccess, onError) {
// loginUser 함수 생성
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
onSuccess(id); // onSuccess 콜백 불러서 id 전달
} else {
onError(new Error('not found')); // onError 콜백 불러서 error('not found') 전달
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
// getRoles 함수 생성
setTimeout(() => {
if (user === 'ellie') {
onSuccess({ name: 'ellie', role: 'admin' }); // onSuccess 콜백 불러서 name, role 전달
} else {
onError(new Error('no access')); //onError 콜백 불러서 error('no access') 전달
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(
id, // id 입력받기
password, // password 입력받기
(user) => {
userStorage.getRoles(
user, // id 전달받은 것
(userWithRole) => {
alert(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
);
},
(error) => {
console.log(error);
}
);
},
(error) => {
console.log(error);
}
);
콜백 체인의 문제점
- 가독성이 떨어진다.
- 디버깅을 하기가 어려워진다.
반응형
'IT > TIL' 카테고리의 다른 글
[TIL19_23.1.27.] [Node] Express - 'westagram' feature/CRUD 코드 수정 (0) | 2023.01.27 |
---|---|
[TIL18_23.1.26.] promise와 async, await (드림코딩 강의) (0) | 2023.01.26 |
[TIL16_23.1.24.] git 공부 & code kata 복습 (0) | 2023.01.24 |
[TIL15_23.1.23.] [Node] Express - 'westagram' 특정 유저 게시글 조회 SQL문 수정 (0) | 2023.01.24 |
[TIL14_23.1.22.] [Node] Express - 'westagram' 게시글 수정, 게시글 지우기, 좋아요 누르기 (0) | 2023.01.23 |