js는 setTimeOut을 실행하거나 서버에서 데이터를 가져오는 등, 오래 걸릴 일들을 기다리지 않고 다음 일부터 처리한다. 이때문에 비동기화가 되고 다시말해 비동기화는 특정 연산이 끝나기 전 이를 기다리지 않고 다음 코드를 먼저 실행하는 것을 말한다.

코드로 살펴보자면 아래 예시에서 데이터를 가져오는 작업을 기다리지 않고, 다음 작업인 console.log를 먼저 실행했기 때문에 undefined가 나오는 현상이다.

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

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

비동기식처리와 콜백함수

이런 js의 비동기를 처리하기 위해 콜백함수를 사용한다. 콜백 함수는 특정 코드가 끝난 후 원하는 동작을 실행시킨다.

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

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

getData에서 서버와 통신해 받은 resopnse를 getData 함수가 끝난 후, callback함수에 넘겨준다. 그리고 callback함수에서 console.log를 바로 실행시킨다.

Promise (resolve, reject, .then, .then.catch)

Promise는 서버에서 데이터를 가져오거나 setTimeOut등 비동기가 일어날 객체이다.