자바스크립트는 특정 코드의 연산이 끝날 때까지 코드의 실행을 멈추지 않고 다음 코드를 먼저 실행하기도 하는데 이를 비동기 처리라고 한다.
function getData(){
var tableData;
$.get('https:/domain.com/products/1',
function(response){
tableData = response;
});
return tableData;
}
console.log(getData()); // undefined
undefined
가 출력되는 이유는 $.get
으로 데이터를 요청하고 받아올 때까지 기다리지 않고 다음 코드인 return tableData
를 실행했기 때문이다console.log('hello');
setTimeout(function(){
console.log('Bye');
}, 3000);
console.log('hello Again');
// hello
// hello Again
// 3초 후 Bye
hello
출력 뒤 3초를 기다렸다가 Bye
가 출력 되는 것이 아닌, hello
를 읽고 Bye
는 3초 뒤로 미루고 hello Again
을 먼저 읽고 3초뒤에 Bye
를 출력한다.Click Event
나 setTimeout
으로 클릭할 때, 혹은 $초 뒤에 특정 액션을 취해야 할 때 그 액션을 함수로 전달하게 되는데 이 때의 함수를 콜백함수라고 부르는 것이다.console.log('hi')
를 실행한다고 했을 때 console.log('hi')
를 실행하도록 지시하는 코드를 함수안에 넣어서 보내는데 이 함수를 콜백함수라고 부른다.블로킹
된다는 단점이 있다.