카테고리 없음

setTimeout을 이용한 비동기 처리

카레공 2022. 5. 25. 12:37

데이터를 받아와서 데이터의 총 갯수를 반환하고 싶은데 기존의 count값이 계속 출력이 되는 문제가 발생했다

함수의 순서를 정해졌고 search한 결과 setTimeout함수를 사용하는것이 제일 간단하다는걸 깨달았다.

//버튼을 클릭하면 데이터를 받아옴
function onClickActBtn() {
  get100response();
}

function get100response() {
  let count = 0;
  for (i = 0; i < 100; i++) {
    axios
      .get("/api/5")
      .then((result) => {
        const data = result.data.result;
        responsedata.push(data);
        const inputArea = document.getElementById("Q5_resData_input_area");
        const p = inputArea.appendChild(document.createElement("p"));
        count++;

        p.append(`count : ${count} `, JSON.stringify(data));
      })
      .catch((err) => {
        const inputArea = document.getElementById("Q5_resData_input_area");
        const p = inputArea.appendChild(document.createElement("p"));
        p.append("서버에서 데이터를 받아오지 못했습니다.");
      });
  }
  
  // 데이터를 받아오는데 2초 내 걸리는걸 확인했고 그 이후에 count를 호출할 수 있게 처리 
  setTimeout(() => {
    const inputArea = document.getElementById("Q5_resData_input_area");
    const p = inputArea.appendChild(document.createElement("p"));
    p.append(`total : ${count} `);
  }, 2500);
}