function getData() {
var tableData;
$.get('https://domain.com/products/1', function(response) {
tableData = response;
});
return tableData;
}
console.log(getData()); // undefined
jQuery의 ajax $.get()
로 데이터를 요청하고 데이터를 받아올 때까지 기다리지 않고 다음 코드인 return tableData;
를 실행(비동기) 했기 때문에 console.log(getData());
에서 getData()
의 결과값은 ajax 응답값이 아니라 초기 값을 설정하지 않은 tableData의 값 undefined
를 출력한다.
Promise로 해결해야함
function getData() {
return new Promise(function(resolve, reject) {
$.get('url 주소/products/1', function(response) {
if (response) {
resolve(response);
}
reject(new Error("Request is failed"));
});
});
}
// 위 $.get() 호출 결과에 따라 'response' 또는 'Error' 출력
getData().then(function(data) {
console.log(data); // response 값 출력
}).catch(function(err) {
console.error(err); // Error 출력
});
promise의 .then() 함수를 이용하여 비동기 호출 시 발생하는 문제를 해결할 수 있음
참고
https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/
https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
https://www.zerocho.com/category/jQuery/post/57c90814addc111500d85a19