(Javascript) Promise를 직접 구현

비동기 처리와 관련하여 가장 먼저 떠오르는 것은 Promise입니다.

Promise 객체를 생성자 함수로 생성하기 때문에

이 생성자 개념을 사용하여 Promise를 직접 구현해 봅시다.

Promise 객체에는 “then”과 “catch”라는 메서드가 있고, 이러한 메서드는 모든 객체가 공유하므로 상속의 개념인 “prototype”이라는 개념을 사용하면 좋을 것입니다.

또한 Promise의 인자로 오는 함수를 실행할 때 함수의 매개변수로 resolve, reject 메서드를 입력해야 합니다.

“resolve” 및 “reject”에 포함된 성공 및 실패 값은 “then” 및 “catch” 메서드를 실행한 후 반환됩니다.

이 약속의 구조와 원칙을 고려하여

다음과 같은 코드를 작성했습니다.

function Promise(cb) {
	Promise.prototype.then = tcb => {
		Promise.prototype.thenFn = tcb;
		return this;
	};

	Promise.prototype.catch = ccb => {
		Promise.prototype.catchFn = ccb;
		return this;
	};

	const resolve = succ => {
		this.state="resolve";
		this.thenFn(succ);
	};

	const reject = err => {
		this.state="reject";
		if (this.catchFn) this.catchFn(err);
	};

	cb(resolve, reject);

	if (new.target) this.state="pending";
}

여기에 사용된 코드를 작성하려면

1. 생성자 기능

2. 프로토타입

3.이 채권

같은 개념을 다시 봐야 했다.

다음 블로그에서 우리는 이 세 가지 개념을 요약할 것입니다!