애니메이션 버튼을 클릭하면 해당 고양이 영상이 실행된다
callback
promise
async & await
function runCallback() {
resetTitle(); // 제목 초기화
playVideo(); // 영상 재생
delay(1000, () => { // 1초 뒤에 영상이 틀어지고 제목을 표시함
pauseVideo();
displayTitle();
delay(500, () => { // 0.5초(?) 뒤에 제목 강조
highlightTitle();
delay(2000, resetTitle); // 2초 뒤에 제목 초기화
});
});
}
function resetTitle() {
log('제목을 초기화합니다');
title.classList.remove('visible', 'highlight');
function playVideo() {
log('영상을 재생합니다');
player.play();
}
function highlightTitle() {
log('제목을 강조합니다');
title.classList.add('highlight');
}
// ! promise callback hell을 벗어날 수 있게 하는 테크닉
// ! promise 1 [resolve()] Go to Next Action
// ! promise 1 [reject()] Handle Error
// 콜백을 인자로 받지 않는다(reslove, reject를 인자로 받음), 새로운 promise 인스턴스를 리턴
// .then() : 작업이 끝나면 다음 작업을 해 줘
// .catch() : Handle Error 마지막 chain 과정에서 해 줌
// promise hell을 방지하기 위해서 리턴 처리를 잘해 주자...!
function runPromise() {
resetTitle();
playVideo();
sleep(1000)
.then(() => {
pauseVideo();
displayTitle();
})
.then(sleep.bind(null, 500))
.then(highlightTitle)
.then(sleep.bind(null, 2000))
.then(resetTitle);
}
//! Async await promise인데 보이는 게 좀 다르다...?
//! await: 비동기 함수들을 마치 동기적인 프로그램인 것처럼 쓸 수 있다
async function runAsync() {
resetTitle();
playVideo();
await sleep(1000);
pauseVideo();
displayTitle();
await sleep(500);
highlightTitle();
await sleep(2000);
resetTitle();
}
const delay = (wait, callback) => {
setTimeout(callback, wait);
}
const sleep = (wait) => {
return new Promise((resolve) => {
setTimeout(resolve, wait);
});
}
resolve
와 reject
는 각각 무엇을 의미하나요?[resolve()] Go to Next Action
비동기 실행이 제대로 동작했을 때 작동
[reject()] Handle Error
비동기 실행 중 실패나 에러가 발생했을 때 작동
sleep
함수를 아래와 같이 수정합니다.
const sleep = (wait) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("hello");
}, wait);
});
};
runPromise
함수를 다음과 같이 수정합니다.
function runPromise() {
resetTitle();
playVideo();
sleep(1000)
.then((param) => {
console.log(param);
pauseVideo();
displayTitle();
return "world";
})
.then((param) => {
console.log(param);
return sleep(5000);
})
.then(highlightTitle)
.then(sleep.bind(null, 2000))
.then(resetTitle);
}
new Promise()
를 통해 생성한 Promise 인스턴스에는 어떤 메서드가 존재하나요? 각각은 어떤 용도인가요?
Promise 인스턴스
Promise.prototype.then
메서드는 무엇을 리턴하나요?
resolve의 값을 받아 리턴
Promise.prototype.catch
메서드는 무엇을 리턴하나요?
비동기가 제대로 작동되지 않은 reject의 값을 받아 리턴
catch
를 테스트해 보고 싶다면, sleep
함수를 다음과 같이 수정합니다.
const sleep = (wait) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('에러'));
}, wait);
});
};
runPromise
함수의 Promise 사용 부분에 catch
메소드를 붙여 봅니다.
1
2
3
4
5
// 생략
.then(resetTitle)
.catch(err => {
console.log(err);
})
Promise의 세 가지 상태는 각각 무엇이며, 어떤 의미를 가지나요?
promise 3가지 State (프로미스 처리 과정)
await
키워드 다음에 등장하는 함수 실행은 어떤 타입을 리턴할 경우에만 의미가 있나요?
await는 async와 짝꿍으로 function 앞에 async를 붙여준 다음에 비동기 적으로 실행되는 것들 앞에 await를 붙여줘서 사용
await의 뒷 부분은 프로미스 타입을 반환하는 것들
await
키워드를 사용할 경우, 어떤 값이 리턴되나요?
promise 값이 리턴
sleep
함수를 아래와 같이 바꿉니다.
const sleep = (wait) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("hello");
}, wait);
});
};
[코드] 수정한 sleep 함수
브라우저 개발자 도구의 콘솔을 열어 다음을 실행해 본 후, returnValue
에 담긴 값을 확인해 보세요.
1
let returnValue = await sleep(1000);