深入JavaScript Day21 - 手写实现Promise
2022-01-24 本文已影响0人
望穿秋水小作坊
一、手写分步骤实现Promise(对于掌握回调函数的奥义也很有帮助)
1、实现executor的传递,并且为executor带上resolve、reject参数
class HYPromise {
constructor(executor) {
const resolve = () => {
console.log("resolve被调用");
};
const reject = () => {
console.log("reject被调用");
};
executor(resolve, reject);
}
}
const myPromise = new HYPromise((resolve, reject) => {
// 这里省略【执行一堆逻辑】
resolve();
});
2、实现同一个promise对象,它的 resolve 和 reject 只能有一个被调用
const PROMISE_STATUS_PENDING = "pending";
const PROMISE_STATUS_RESOLVED = "resolved";
const PROMISE_STATUS_RJECTED = "rejected";
class HYPromise {
constructor(executor) {
const resolve = () => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_RESOLVED;
console.log("resolve被调用");
}
};
const reject = () => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_RJECTED;
console.log("reject被调用");
}
};
this.status = PROMISE_STATUS_PENDING;
executor(resolve, reject);
}
}
const myPromise = new HYPromise((resolve, reject) => {
// 这里省略【执行一堆逻辑】
reject();
resolve();
});
3、加入then函数,并实现其逻辑。
const PROMISE_STATUS_PENDING = "pending";
const PROMISE_STATUS_RESOLVED = "resolved";
const PROMISE_STATUS_RJECTED = "rejected";
class HYPromise {
constructor(executor) {
const resolve = (value) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_RESOLVED;
this.value = value;
console.log("resolve被调用");
queueMicrotask(() => {
this.onResolved(this.value);
});
}
};
const reject = (reason) => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_RJECTED;
this.reason = reason;
console.log("reject被调用");
queueMicrotask(() => {
this.onRejected(this.reason);
});
}
};
this.status = PROMISE_STATUS_PENDING;
executor(resolve, reject);
}
then(onResolved, onRejected) {
this.onResolved = onResolved;
this.onRejected = onRejected;
}
}
const myPromise = new HYPromise((resolve, reject) => {
// 这里省略【执行一堆逻辑】
resolve(222);
reject(111);
});
myPromise.then(
(res) => {
console.log("then res", res);
},
(err) => {
console.log("then err", err);
}
);