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 |
Tags
- reactivity
- const
- es6
- composition api
- await
- ref
- asynchronus
- Component
- tdz
- composition API
- 앱 빌드
- vue
- 오블완
- async
- mobile dev tools
- 티스토리챌린지
- eruda
- promise
- hoisting
- synchronus
- watch
- setup 함수
- vitre
- watchEffect
- html 엔티티
- dex모드
- 템플릿 문법
- drective
- computed
- let
Archives
- Today
- Total
uxtry
es6: Promise(프로미스) 본문

ES6에서 도입된 Promise는 비동기 작업을 처리하고, 콜백 헬(callback hell)을 해결하기 위한 객체입니다. Promise는 주로 비동기 작업(예: 네트워크 요청, 파일 읽기 등)을 처리할 때 사용되면, 작업이 성공하거나 실패했을 때 특정 작업을 실행할 수 있게 해줍니다.
1. Promise의 기본 구조
Promise 객체는 다음 3가지 상태를 가집니다.
- pending (대기): 초기 상태로, 작업이 완료되지 않은 상태
- fulfilled (이행): 작업이 성공적으로 완료된 상태
- rejected (거부): 작업이 실패한 상태
const promise = new Promise ((resolve, reject) => {
//비동기 작업을 수행.
const success = true; //예시: 작업이 성공했다고 가정
if(success){
resolve("작업 성공!"); //작업 성공 시 resolve 호출
}else{
reject("작업 실패!"); //작업 실패 시 reject 호출
}
});
2. then과 catch로 결과 처리하기
- then: Promise가 이행(fullfilled)되었을 때 실행할 콜백 함수를 지정합니다.
- catch: Promise가 거부(rejected)되었을 때 실행할 콜백 함수를 지정합니다.
promise
.then((result) => {
console.log(result); // "작업 성공! 출력"
})
.catch((error) => {
console.error(error); // "작업 실패! 출력"
});
3. Promise Chaining (체이닝)
then 메서드는 promise를 반환하기 때문에 여러 개의 then을 연결하여 연속적인 비동기 작업을 수행할 수 있습니다.
const promise = new Promise((resolve) => resolve(1));
promise
.then((result) => {
console.log(result); //1
return result * 2;
})
.then((result) => {
console.log(result); //2
return result * 3;
})
.then((result) => {
console.log(result); //6
})
.catch((error) => {
console.error(error);
});
4. Promise.all
Promise.all 은 여러 개의 Promise가 모두 완료될 때까지 기다렸다가 결과를 배열로 반환합니다. 하나라도 실패하면 전체가 실패로 간주됩니다.
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then((result) => {
console.log(results); //1,2,3
})
.catch((error) => {
console.error(error);
});
5. Promise.race
Promise.race는 여러 개의 Promise 중에서 가장 먼저 완료된 Promise의 결과를 반환합니다.
const promise1 = new Promise((resolve) => setTimeout(resolve, 100, "첫 번째"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 50, "두번째"));
Promise.race([promise1, promise2].then((result) => {
console.log("result"); //"두번째"가 먼저 완료되어 출력됩니다.
});
6.async와 await
ES8에서 추가된 async와 await는 Promise의 문법을 간결하게 만들어줍니다. await 키워드는 Promise가 완료될 때까지 기다린 후 결과를 반환합니다.
async function asyncFunc(){
try{
const result = await new Promise((resolve) =>
setTimeout(() => resolve("비동기 작업 완료!") , 100);
);
console.log("result"); //"비동기 작업 완료!"
} catch (error) {
console.error(error);
}
}
asyncFunc();
Promise는 비동기 코드를 더 깔끔하고 예측 가능하게 작성할 수 있게 해주며, then , catch를 통해 오류 처리를 할 수 있고, async / awiat 와 함께 사용하여 코드 가독성을 높일 수 있습니다.
'ES6 주요 문법 (es6:)' 카테고리의 다른 글
| es6: Import and export(가져오기 및 내보내기) (0) | 2024.10.29 |
|---|---|
| es6: Array and object destructing(배열 및 객체 비구조화) (0) | 2024.10.29 |
| es6: Default parameters (기본 매개 변수) (0) | 2024.10.29 |
| es6: Template Literals(템플릿 리터럴) (0) | 2024.10.29 |
| es6: Arrow function(화살표 함수) (0) | 2024.10.29 |