class CustomPromise {
constructor(executor) {
this.executor = executor;
this.state = 'pending';
this.value = null;
const resolve = (data) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = data;
this.onResolve && this.onResolve(data);
}
};
const reject = (error) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = error;
this.onReject && this.onReject(error);
}
};
this.executor(resolve, reject);
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
} else if (this.state === 'rejected') {
onRejected(this.value);
} else {
this.onResolve = onFulfilled;
this.onReject = onRejected;
}
return this;
}
catch(onRejected) {
if (this.state === 'rejected') {
onRejected(this.value);
} else {
this.onReject = onRejected;
}
return this;
}
}
// 사용 예제
const myPromise = new CustomPromise((resolve, reject) => {
setTimeout(() => {
const isSuccess = true; // 성공 여부를 가정
if (isSuccess) {
resolve('성공 결과');
} else {
reject('오류 메시지');
}
}, 100);
});
myPromise
.then((result) => {
console.log(result); // "성공 결과" 출력
})
.catch((error) => {
console.error(error); // 실행되지 않음
});
chatGPT가 알려줌.
'프론트엔드-코드 > Javascript' 카테고리의 다른 글
제이쿼리 .eq() 같은 거 (0) | 2023.09.25 |
---|---|
랜덤 색상 얻기 (0) | 2023.09.25 |
WebRTC (0) | 2023.09.21 |
Set (0) | 2023.09.21 |
axios 서버에서 데이터 가져오기. (0) | 2023.09.20 |