Open
Description
手撕promise
const STATUS_PENDING = "pending";
const STATUS_RESOLVE = "fulfilled";
const STATUS_REJECT = "rejected";
class Mypromise {
constructor(executor) {
this.status = STATUS_PENDING;
this.value = null;
this.reason = null;
const resolve = (value) => {
if (this.status === STATUS_PENDING) {
queueMicrotask(()=>{
this.status === STATUS_RESOLVE;
this.value = value;
this.onFulfilled(this.value);
})
}
};
const reject = (value) => {
if (this.status === STATUS_PENDING) {
queueMicrotask(()=>{
this.status === STATUS_REJECT;
this.value = value;
this.onReject(this.value);
})
}
};
executor(resolve, reject);
}
then(onFulfilled, onReject) {
this.onFulfilled = onFulfilled;
this.onReject = onReject;
}
}
const promise = new Mypromise((resolve, reject) => {
resolve("测试resolve")
reject("测试reject")
});
promise.then(
(res) => {
console.log(res);
},
(err) => {
console.log(err);
}
);