오늘은 Promise 함수에 대해 공부해보았다.
먼저 Promise 함수란 비동기 작업의 완료 또는 실패와 그 결과 값을 알려 달라는 약속이다. JavaScript 에서는 주로 비동기 작업을 다룰 때 사용된다. 또한 Promise는 세 가지 상태를 가진다.
const myPromise = new Promise((resolve, reject) => {
// 비동기 작업 수행
// 성공 시 resolve 호출
// 실패 시 reject 호출
});
resolve 는 비동기 작업이 성공적으로 완료되었을 때 호출된다. 이 함수를 호출하면 Promise 객체는 Fulfilled(이행됨) 상태가 되며, .then() 메서드에 등록된 콜백 함수가 실행되게 된다.
const myPromise = new Promise((resolve, reject) => {
// 비동기 작업 성공
resolve('작업 성공!');
});
myPromise.then(result => {
console.log(result); // '작업 성공!'
});
하지만 만약 비동기 작업이 실패하게 된다면 reject 함수가 호출된다. 이 함수를 호출하면 Rejected(거부됨) 상태가 되며, .catch() 메서드에 등록된 콜백 함수가 실행된다.
const myPromise = new Promise((resolve, reject) => {
// 비동기 작업 실패
reject(new Error('작업 실패!'));
});
myPromise.catch(error => {
console.error(error); // Error: 작업 실패!
});
Promise 함수는 async/await 을 사용해 동일한 작업을 수행 하지만 .then을 사용할 때 보다 좀 더 가독성 있고, 간결하게 만들 수 있다.
e.g
async/await 사용
async function simulateAsyncAwait() {
try {
console.log('작업 시작 (async/await)');
// 비동기적으로 2초 대기
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('작업 완료 (async/await)');
} catch (error) {
console.error('에러 발생 (async/await):', error);
}
}
// 함수 호출
simulatekAsyncAwait();
.then 사용
function simulateThen() {
console.log('작업 시작 (.then())');
// 비동기적으로 2초 대기
new Promise(resolve => setTimeout(resolve, 2000))
.then(() => {
console.log('작업 완료 (.then())');
})
.catch(error => {
console.error('에러 발생 (.then()):', error);
});
}
// 함수 호출
simulateThen();
이렇게 Promise 함수에 대해 공부해 보았다. 뭔가 한 가지를 공부하다 보면
그 한 가지에 관련된 또 여러 가지 개념들 역시 공부해야 된다는 게 어렵고 힘든 것 같지만 그 여러 가지 개념들까지 같이 공부함으로써 더 잘 이해할 수 있게 되는 것 같다