javascript
[javascript] Promise
TTTGGG
2024. 7. 12. 11:29
728x90
반응형
SMALL
Promise
- javascript에서 비동기 작업을 처리하기 위한 객체
- 비동기 작업이 성공적으로 완료되었는지, 실패했는지 또는 아직 진행 중인지를 나타내는 값
Promise는 다음 세 가지 상태를 가질 수 있음
- Pending: 비동기 작업이 아직 완료되지 않은 상태
- Fulfilled: 비동기 작업이 성공적으로 완료된 상태
- Rejected: 비동기 작업이 실패한 상태
Promise 사용
const myPromise = new Promise((resolve, reject) => {
const success = true; // 비동기 작업의 성공 여부를 나타내는 플래그
if (success) {
resolve("The operation was successful!"); // 작업이 성공했을 때 호출
} else {
reject("The operation failed."); // 작업이 실패했을 때 호출
}
});
/*
then은 Promise가 Fulfilled 상태가 되었을 때 실행
catch는 Promise가 Rejected 상태가 되었을 때 실행
*/
myPromise
.then((message) => {
console.log(message); // "The operation was successful!"
})
.catch((error) => {
console.error(error); // "The operation failed."
});
병렬 처리
function taskA() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Task A completed');
resolve();
}, 1000);
});
}
function taskB() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Task B completed');
resolve();
}, 1000);
});
}
Promise.all([taskA(), taskB()])
.then(() => {
console.log('All tasks completed');
});
순차적 처리
function task1() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Task 1 completed');
resolve();
}, 1000);
});
}
function task2() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Task 2 completed');
resolve();
}, 1000);
});
}
task1()
.then(() => task2())
.then(() => {
console.log('All tasks completed');
});
728x90
반응형
LIST