종우의 컴퓨터 공간
★[ES6] Promises 본문
What is Promises?
- alternative to callbacks
- alternative way of handling asynchronous operations
- the reason why they are called promises is that while they are handling asynchronous operations, they can promise to do something when that operation is finished
프라미스란?
- 프라미스는 자바스크립트 비동기 처리에 사용되는 객체이다. 여기서 자바스크립트의 비동기 처리란 '특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성'을 의미한다.
프라미스가 필요한 이유?
- 프라미스는 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용한다. 일반적으로 웹 앱을 구현할 때 서버에서 데이터를 요청하고 받아오는데 데이터를 받아 오기도 전에 데이터를 다 받아온 것 마냥 화면에 데이터를 표시하려고 하면 오류가 발생하거나 원하는 상황이 발생하지 않는다. 이와 같은 문제점을 해결하기 위한 방법 중 하나가 프라미스이다.
프라미스의 상태
- 프라미스는 상호 배타적인 세 가지 상태를 가진다.
- 처리됨(fulfilled): 프라미스와 관련된 작업이 성공적으로 수행됨
- 거부됨(rejected): 프라미스와 관련된 작업이 실패함
- 보류됨(pending): 처리되거나 거부되지 않은 상태
- 프라미스의 결과는 성공(fulfilled)하거나 실패(rejected)하거나 단 두가지 뿐이며, 이 때 결정됐다라고 표현한다. 확실한 성공 혹은 실패 두가지 중 단 하나만 딱 한번 일어난다. 성공했다가 실패하는 경우는 없다.
예제
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 = false; // just to mimic the error
if (!error) {
resolve();
} else {
reject('Error: Something went wrong!');
}
}, 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 the post three'})
.then(getPosts)
.catch(function(err) {
console.log(err);
});
- return new Promise(function(resolve, reject) {});
- resolve()는 .then()과 함께 사용되고, reject()는 .catch()와 함께 사용된다.
'자바 스크립트 (JavaScript) > Asynchronous JS, Ajax & Fetch API' 카테고리의 다른 글
★[ES6]Arrow Functions (0) | 2021.08.13 |
---|---|
★[ES6]Fetch API (0) | 2021.08.13 |
Custom HTTP Library (Ajax with Callbacks) (0) | 2021.08.11 |
Callback Functions (0) | 2021.08.11 |
REST API & HTTP Requests (0) | 2021.08.11 |