7주차 사전과제
: Promise, Fetch API, Axios 참고문서 참고해서 공부하고 정리하기
자바스크립트에서 Promise는 비동기 처리에 활용되는 객체로, 주로 웹서비스를 구현할 때 원활한 데이터 통신을 위해 활용된다.
웹 페이지에서 서버로 데이터를 요청했을 때, 데이터를 모두 받기 전 출력하려고 하는 경우를 방지하기 위해 활용된다.
➡️ Promise 객체는 비동기 로직을 마치 동기처럼 사용할 수 있는 기능을 가진다.
비동기 로직인 A, B, C 로직이 있다고 했을 때, 이를 Promise
를 사용하지 않고 실행시키면 먼저 로직이 끝나는 순서로 출력이 되지만 Promise
를 사용하면 A, B, C 순서대로 출력시킬 수 있다.
Promise
객체가 생성되고 종료될 때까지는 3개의 상태를 갖는다.
- Pending(대기): 비동기 로직 처리의 미완료 상태
- Fulfilled(이행): 비동기 로직 처리가 완료된 상태로
Promise
결괏값 반환 상태- Rejected(실패): 비동기 로직 처리의 실패 또는 오류 상태
new Promise();
Promise
객체를 생성하면 대기(Pending) 상태이다.
new Promise((resolve, reject) => {});
new Promise()
메서드 호출시 콜백 함수를 선언할 수 있으며, 인자로는 resolve(실행)
와 reject(실패)
를 가진다.
new Promise(function(resolve, reject) {
resolve();
});
콜백함수 인자인 resolve
를 실행하면 이행(완료)된 상태이다.
function getData() {
return new Promise((resolve, reject) => {
let data = 100;
resolve(data);
})
}
getData().then((resolvedData) => console.log(resolvedData));
>> 100 // 결과
이행 상태가 되면 then()
을 활용하여 결괏값을 받을 수 있다.
new Promise(function(resolve, reject) {
reject();
});
reject
호출 시 실패 상태가 된다.
function getData() {
return new Promise((resolve, reject) => {
reject(new Error("This is rejected!"));
})
};
getData().catch((err) => console.log(err));
>> Error: This is rejected!
... 에러메시지 ...
resolve
와 마찬가지로, 실패상태가 되면 catch()
를 활용하여 결괏값을 받고, 예외처리까지 가능하다.
const promise = () => new Promise((resolve, reject) => {
let a = 1 + 1;
if(a==3) {
resolve('success');
} else {
reject('failed');
}
});
promise().then((message) => {
console.log('This is in the then ' + message)
}, (error) => {
console.log('This is in the then ' + error)
});
>> This is in the then failed
const promise = () => new Promise((resolve, reject) => {
let a = 1 + 1;
if(a==3) {
resolve('success');
} else {
reject('failed')
}
});
promise().then((message) => {
console.log('This is in the then ' + message)
}).catch((error) => {
console.log('This is in the catch ' + error)
});
>> This is in the then failed
then
메서드와 catch
메서드 둘 다 모두 에러처리가 가능하나, then
메서드로 에러처리를 할 경우에는 에러를 잡아내지 못하는 경우도 존재하므로 더 많은 상황의 예외를 처리할 수 있는 catch
메서드를 사용하는 게 좋다.
Promise
는 후속처리 메서드를 체이닝하여 Promise
를 반환하는 여러 개의 비동기 함수들을 연결해서 사용할 수 있다.
const promise = (result) => {
return new Promise((resolve, reject) => {
if(result == 'success')
resolve('success');
else
reject('failed');
});
}
promise('success')
.then(promise)
.then(message => console.log('This is in the then ' + message))
.catch(error => console.log('This is in the catch ' + error))
>> This is in the then success
첫 번째로 호출한 비동기함수 Promise
의 결과값을 후속처리 메서드 then
을 통해 두 번째 Promise
로 전달하였고, 그 결과값을 메세지로 출력한다.
Promise
를 반환한다. (fullfiled)Promise
를 반환한다. (rejected)Promise
가 담겨있는 배열과 같은 iterable 객체를 인자로 받는다.Promise
를 병렬로 처리하고 그 결과값을 배열에 담아 resolve로 반환한다.Promise
를 수행하던 도중 하나라도 에러가 발생하면 rejected 상태가 되고 수행을 종료한다.Promise
가 담겨있는 iterable 객체를 인자로 받고, 병렬로 처리하지 않고 가장 먼저 끝나는 Promise
의 결과값을 resolve로 반환한다.Promise
가 담겨있는 iterable 객체를 인자로 받고 병렬로 처리한다.Promise.all
과 달리 중간에 rejected 상태가 되어도 수행을 종료하지 않고 수행된 상태와 결과값을 배열에 담아 resolve로 반환한다.