Javascript/vanilla

자바스크립트 비동기처리와 콜백함수

브라더 코드 2021. 2. 11. 15:19

비동기 처리(ajax)

function getData() {
	var tableData;
	$.get('https://brother.com/products/1', function(response) {
		tableData = response;
	});
	return tableData;
}

console.log(getData()); // undefined

-> $.get()로 데이터를 요청하고 받아올 때까지 기다려주지 않고 다음 코드인 return tableData;를 실행했기 때문에 getData()의 결과 값은 초기 값을 설정하지 않은 tableData의 값 undefined를 출력.

콜백함수로 비동기 처리 문제점 해결하기

function getData(callbackFunc) {
	$.get('https://brother.com/products/1', function(response) {
		callbackFunc(response); 
		// 서버에서 받은 데이터 response를 callbackFunc() 함수에 넘겨줌});
}

getData(function(tableData) {
	console.log(tableData); // $.get()의 response 값이 tableData에 전달됨});

-> 콜백 함수를 사용하면 특정 로직이 끝났을 때 원하는 동작을 실행시킬 수 있다.