While문 api 호출 리펙토링(setTimeout, setInterval)
본문 바로가기

Frontend/모던자바스크립트

While문 api 호출 리펙토링(setTimeout, setInterval)

while문으로 api를 호출하는 코드로 짰더니 맙소사,

리턴값이 적절할때까지 호출해야하는데 카운트를 세보니 최소 수백개의 API를 호출하였다.

리펙토링이 시급하다.

class Test{
  //원하는것 a, 1~5, b, c
  async funcA(){console.log('a')}
  
  async funcB(){
    while(1){
      const test = await fetch(`...`).then(data => data.json())
      console.log(test.result)
      if(test.result){
        break;
      }
    }
    console.log('b')
  }
  
  async funcC(){console.log('c')}
}

const test = new Test()

const use = async() => {
  await test.funcA()//a
  await test.funcB()
  await test.funcC()//c
}
use()

 

setTimeout()

funcB() 를 1초마다 호출하는 setTimeout()으로 변경해보자

...
async funcB(){
    function check() {
        fetch(`...`).then(data => data.json())
          .then((test) => {
            console.log(test.result);
            if (test.result) {
              return false;//check()종료
            } else {
              setTimeout(check, 1000);//재귀호출
            }
          });
      }
  	check();
    console.log('b')
  }
...

혹은 그냥 일정시간이후에(잠깐기다렸다가) 호출하는방법도있다.

const test = async() => {
    console.log('hello')
    await new Promise(r=>setTimeout(r, 1000 * 5))
    console.log('hi')//5초후 호출
}
test()

 

setInterval()

setInterval로 변경하였는데 자바스크립트 엔진에 의해 funcB()의 결과값과는 상관없이 b를 바로 출력한뒤에 다음 funcC()로 넘어가버렸다.

promise로 감싸서 해결

...
async funcB(){
    await new Promise((res, rej)=>{
      let count = 0
      let interval = setInterval(function() {
        if (count < 5) {
          count++
          console.log(count)
        } else {
          console.log("stopped")
          clearInterval(interval)
          res()
        }
      }, 500)
    })
    console.log('b')
  }
...

console

반응형