
자바스크립트 비동기 처리에 사용되는 객체. 보통 서버와 클라이언트간의 통신에서 주로 사용된다.
Promise는 다음 중 하나의 상태를 가진다.
new Promise(function (resolve, reject) {
// ...
});
function getData() {
return new Promise(function (resolve, reject) {
var data = 100;
resolve(data);
});
}
// resolve()의 결과 값 data를 resolvedData로 받음
getData().then(function (resolvedData) {
console.log(resolvedData); // 100
});
function getData() {
return new Promise(function (resolve, reject) {
reject(new Error("Request is failed"));
});
}
// reject()의 결과 값 Error를 err에 받음
getData()
.then()
.catch(function (err) {
console.log(err); // Error: Request is failed
});
promise 에러 처리 방법으로는 두 가지가 있다.
첫 번째 방법은 then()의 첫 번째 콜백 함수 내부에서 오류가 나는 경우엔 제대로 잡아내지 못하므로, 가급적 오류는 catch()로 처리하는 것이 바람직하다.
function getData() {
return new Promise({
// ...
});
}
// then() 으로 여러 개의 프로미스를 연결한 형식
getData()
.then(function (data) {
// ...
})
.then(function () {
// ...
})
.then(function () {
// ...
});
callback hell을 벗어나기 위해 사용.
함수 앞에 async, 비동기 처리할 코드 앞에 await을 사용.
const getSomthing = async () => {
await doSomething();
};