2021 프론트 엔드 로드맵 따라가기/JS
ES6 Promise
알 수 없는 사용자
2021. 6. 9. 03:40
비동기 작업의 다른 방법으로는 ES6에서 추가된 Promise 객체를 이용하는 방법이 있습니다.
Promise라고 붙여진 이름처럼 비동기 처리를 완료한 뒤 특정한 작업을 수행하기로 '약속' 합니다.
resolve 인자는 비동기요청이 끝나고 수행할 함수를 전달받기 위함이며, reject 인자는 요청 중 에러가 발생했을 때 수행할 함수를 전달받기 위해 존재합니다.
resolve 인자는 Promise 객체의 then 메서드를 통해 비동기 처리완료 시 수행될 함수를 전달받고, reject 인자는 catch 메서드를 통해 함수를 전달받습니다.
const posts = [
{title: "Post one", body: "this is post one"},
{title: "Post two", body: "this is post two"}
];
function createPost(post) {
return new Promise(function(resolve, reject) {
setTimeout(function () {
posts.push(post);
const error = true;
if (error) {
reject("Error: Something went Wrong");
} else {
resolve();
}
}, 2000);
});
}
function getPosts() {
setTimeout(function () {
let output = "";
posts.forEach(function(post) {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
}, 1000);
}
createPost({title: "Post three", body: "this is post three"})
.then(getPosts)
.catch(function (err) {
console.error(err);
});