[JS-FINAL] 10. 비동기, Promise

게코젤리·2023년 5월 30일

비동기의 이해

setTimeout(() => console.log('hi'), 0);
for(let i = 0; i< 1000000; i++){
    console.log(i);
}

위 코드에서 setTimeout 함수는 "1밀리초 후에 'hi'를 출력하라"고 JavaScript에 지시한다. 그런데 중요한 점은, 이것이 바로 실행되는 것이 아니라 '예약'되는 것이라는 점이다.

동기적 코드(for문)가 모두 끝난 다음에야 호출 스택이 비어 예약한 console.log('hi')를 실행하게 된다.

setTimeout의 두번째 인자의 시간은 콜백 함수가 실행되는 최소 시간이지 보장된 시간이 아니다.

Promise

const setTimer = duration => {
    const promise = new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve('Done');
        }, duration);
    })
    return promise;
}

setTimer(2000).then(data => {
    console.log(data);
})
  • 프로미스 체이닝
setTimer(2000)
  .then(data => {
    console.log(data);
    return setTimer(3000);
  })
  .then(data => {
    console.log(data);
  });
  • 오류 처리
const setTimer = duration => {
    const promise = new Promise((resolve, reject) => {
        if (duration > 5000) {
            reject('Too long duration');
        } else {
            setTimeout(() => {
                resolve('Done');
            }, duration);
        }
    })
    return promise;
}

setTimer(2000).then(data => {
    console.log(data);
}).catch(error => {
    console.error(error);
});

0개의 댓글