munifico.github.io

munifico's anything page

Follow me on GitHub

프라미스 체인

프라미스에는 체인으로 연결할 수 있다는 장점이 있습니다. 즉, 프라미스가 완료되면 다른 프라미스를 반환하는 함수를 즉시 호출할 수 있습니다. launch 함수를 만들어 카운트다운이 끝나면 실행되게 해 봅시다.

function launch() {
    return new Promise((resolve, reject) => {
        console.log('Lift off!');
        setTimeout(() => {
            resolve('In orbit!');
        }, 2*1000); //2초만에 궤도에 도달!
    });
}

이 함수를 카운트다운에 쉽게 묶을 수 있습니다.

const p = new Countdown(5);
p.on('tick', i => console.log(i + '...'));    
p.go()
    .then(launch)
    .then(msg => console.log(msg))
    .catch(err => console.error('Houston, we have a problem...'));

/*
5...
4...
3...
2...
1...
0...
Lift off!
In orbit!
*/

프라미스 체인을 사용하면 모든 단계에서 에러를 캐치할 필요는 없습니다. 체인 어디에서는 에러가 생기면 체인 전체가 멈추고 catch 핸들러가 동작합니다. 카운트다운을 15초로 바꾸고 실행해 보십시오. launch는 실행되지 않습니다.

const p = new Countdown(15, true);
p.on('tick', i => console.log(i + '...'));    
p.go()
    .then(launch)
    .then(msg => console.log(msg))
    .catch(err => console.error('Houston, we have a problem...'));

/*
15...
14...
Houston, we have a problem...
*/

이전 : 이벤트
다음 : 결정되지 않는 프라미스 방지하기
목차