|
0. 동기와 비동기 개념 1. 동기와 비동기 장단점 비동기 예시, AJAX 비동기 예시, setTimeout() 3. 콜백 함수, 비동기 처리 방식의 문제점 해결 4. 콜백 지옥 (Callback hell) 5. 비동기 처리의 이유 |
0. 동기와 비동기 개념
1. 동기와 비동기 장단점
동기와 비동기는 상황에 따라서 각각의 장단점이 있다.
2. 동기와 비동기 예시
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
비동기 예시, AJAX
function getData() {
var tableData;
$.get('https://domain.com/products/1', function(response) {
tableData = response;
});
return tableData;
}
console.log(getData());
==================================================================
결과 : undefined
비동기 예시, setTimeout()
setTimeout(foo, 3000);
function boo(){
console.log("2");
}
console.log("1");
3. 콜백함수, 비동기 처리 방식의 문제점 해결
function getData(callbackFunc) {
$.get('https://domain.com/products/1', function(response) {
callbackFunc(response);
/서버에서 받은 데이터 response를 callbackFunc() 함수에 넘겨줌.
});
}
getData(function(tableData) {
console.log(tableData);
/$.get()의 response 값이 tableData에 전달됨
});
4. 콜백 지옥 (Callback hell)
$.get('url', function(response) {
parseValue(response, function(id) {
auth(id, function(result) {
display(result, function(text) {
console.log(text);
});
});
});
});
5. 비동기적 처리의 이유
![[JavaScript] 비동기 통신과 AJAX: 동기·비동기, 콜백 함수, 콜백 지옥](/posts/async-ajax-callback/images/image_1.jpg)