Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- es6
- JS
- css variables
- 정규표현식
- node
- Node.js
- close together
- express-handlebars
- module wrapper function
- css 오버레이
- flex-grow
- Engoo
- ajax
- 디자인패턴
- Sass
- Express
- 무료 백엔드 배포
- flex-shrink
- improve-iq-by-up-to-10%!
- flex-basis
- Prototype
- img 확대
- select by attribute
- css
- just-one-small-sip
- shit-christmas
- regExp
- css grid
- flexbox
- Object.create
Archives
- Today
- Total
ES6 Promise 본문
비동기 작업의 다른 방법으로는 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);
});
'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글
ES6 Arrow Function (0) | 2021.06.09 |
---|---|
ES6 Fetch API (0) | 2021.06.09 |
AJAX POST request (0) | 2021.06.07 |
AJAX 이용 시 주의할 점 (0) | 2021.06.07 |
Callback function (0) | 2021.06.07 |
Comments