트러블슈팅
JavaScript 비동기 처리 문제
인삼추출물
2020. 3. 9. 17:52
chart설정
var ctx = document.getElementById("myAreaChart");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: generateLabels()
});
label설정
function generateLabels() {
var labels = [];
lineDbData.getLineUph({line:lineValue}, function(result){
labels = Object.getOwnPropertyNames(result)
console.log("1 : " + labels);
});
console.log("2 : " + labels);
return labels;
}
결과
발생원인 : chart data에 비동기 접근을 통한 DB data를 셋팅하는 시점과 화면에 표시하는 시점의 차이에 따른 출력Error
실제로 출력 결과를 보면 2번이 먼저 출력되고 1번이 모든 처리를 끝내고 출력되는 걸 확인할 수 있습니다.
해결방법 :
① promise, async, await 비동기 함수대응 객체를 활용한 대기후 실행 방법을 사용합니다.
② 비동기 처리 방식을 동기로 바꿉니다.
예를 들어 label 설정 getLineUph에서 ajax로 data를 받아오고 있다면
$.ajax({
url:'url',
dataType:'json',
async: false,
contentType:'application/json',
data:JSON.stringify({param}),
method:'POST',
success:function(t){
getInfo = t
},
error:function(){
getInfo = null
}
})
async: false 를 사용해 동기로 바꿔주면 됩니다.