Promise Process
Promise를 이용한 비동기 통신의 진행 순서입니다.
by falsy
HTML
<div id="text">
</div>
CSS
#text {
font-size: 14px;
line-height: 22px;
}
JavaScript
function testPromise() {
return new Promise((resolve, reject) => {
document.getElementById('text').innerText += '2. 약 1초가 걸리는 비동기 통신을 가정하여 setTimeout을 사용합니다.\n';
setTimeout(() => {
resolve('success');
document.getElementById('text').innerText += '3. resolve가 실행되어 현재의 Promise의 상태가 "대기(pending)"에서 "이행(fulfilled)"으로 변경되며 "success"라는 "이행값(fulfilled value)"을 가지고 있습니다.\n';
reject("failure reason");
document.getElementById('text').innerText += '4. reject를 만났지만 현재 Promise의 상태가 "대기(pending)"가 아니기 때문에 무시됩니다.\n';
document.getElementById('text').innerText += '5. resolve, reject 모두 return을 의미하지는 않기 때문에 스코프 안의 이후 코드는 모두 실행이 됩니다.\n';
}, 1000);
});
}
document.getElementById('text').innerText += '1. testPromise() 함수를 호출하며 Promise를 이용한 통신을 시작합니다. 그리고 (대기, 성공, 실패)의 상태를 가지고 있는 Promise객체를 request라는 변수에 담습니다.\n';
const request = testPromise();
setTimeout(() => {
document.getElementById('text').innerText += '6. 조금 더 Promse를 이해하기 위해 "request"라는 변수에 확실히 통신이 완료된 값을 가지고 있을거라 예상할 수 있는 3초 후에 then 메소드를 호출합니다.\n';
request.then(res => {
document.getElementById('text').innerText += '7. 현재 시점에서 request라는 변수에는 "이행(fulfilled)"상태에 "success"라는 "이행값(fulfilled value)"을 가지고 있는 Promse 객체를 담고 있습니다.\n';
console.log(res);
document.getElementById('text').innerText += `8. Promse 객체가 이행했기 때문에 then 메서드의 첫번째 인자에 이행값을 가지고 있는 함수가 실행됩니다. 성공한 이행값은 '${res}' 입니다.`;
}).catch(err => {
// Promise의 상태가 거부가 아니기 때문에 호출되지 않습니다.
console.log(res);
});
}, 3000);