🛠️ 처음부터 만드는 Promise — 비동기 처리의 핵심 이해하기
왜 Promise를 직접 만들어볼까?
Promise는 비동기 JavaScript의 근간입니다. 직접 구현하면 `then` 체이닝, 상태 전이, 마이크로태스크 큐의 동작 원리를 깊이 이해할 수 있습니다.
구현
```js
class MyPromise {
#state = 'pending';
#value = undefined;
#callbacks = [];
constructor(executor) {
const resolve = (value) => this.#transition('fulfilled', value);
const reject = (reason) => this.#transition('rejected', reason);
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
#transition(state, value) {
if (this.#state !== 'pending') return; // 상태는 한 번만 변경
this.#state = state;
this.#value = value;
queueMicrotask(() => this.#callbacks.forEach((cb) => cb()));
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
const handle = () => {
const handler = this.#state === 'fulfilled' ? onFulfilled : onRejected;
const fallback = this.#state === 'fulfilled' ? resolve : reject;
if (typeof handler !== 'function') return fallback(this.#value);
try {
const result = handler(this.#value);
result instanceof MyPromise
? result.then(resolve, reject)
: resolve(result);
} catch (err) {
reject(err);
}
};
this.#state === 'pending'
? this.#callbacks.push(handle)
: queueMicrotask(handle);
};
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
```
사용 예시
```js
new MyPromise((resolve) => setTimeout(() => resolve(1), 100))
.then((v) => v + 1)
.then((v) => console.log(v)); // 2
```
핵심 포인트
> 📖 [MDN — Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise) · [Promises/A+ 스펙](https://promisesaplus.com/)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!