then 方法的回调函数是异步执行,需要等同步代码都执行完以后才会执行
示例
const p = new Promise((resolve, reject) => {
resolve("ok");
console.log(111);
});
p.then(
(value) => {
console.log(222);
},
(reason) => {}
);
console.log(333);
// 正常结果应该是
// 111
// 333
// 222
// 但是我们目前的是
// 111
// 222
// 333
这样就不对
所以还要对then()进行修改
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value
}
return new Promise((resolve, reject) => {
function callback(type) {
try {
let result = type(self.PromiseResult);
if (result instanceof Promise) {
result.then(
(v) => {
resolve(v);
},
(r) => {
reject(r);
}
);
} else {
resolve(result);
}
} catch (e) {
reject(e);
}
}
if (this.PromiseState === "resolved") {
// 为了让 then() 方法异步执行加一个定时器
setTimeout(() => {
callback(onResolved);
})
}
if (this.PromiseState === "rejected") {
// 为了让 then() 方法异步执行加一个定时器
setTimeout(() => {
callback(onResolved);
})
}
if (this.PromiseState === "pending") {
this.callbacks.push({
onResolved: function () {
callback(onResolved);
},
onRejected: function () {
callback(onRejected);
},
});
}
});
};
还有异步任务的情况,此时要修改Promise函数
function Promise(executor) {
const self = this
this.PromiseState = 'pending'
this.PromiseResult = null
this.callbacks = [];
function resolve(data) {
if (self.PromiseState !== 'pending') return
self.PromiseState = 'resolved'
self.PromiseResult = data
// 为了让then()方法变成异步的,需要加定时器
setTimeout(() => {
self.callbacks.forEach((item) => {
item.onResolved(self.PromiseResult);
});
})
}
function reject(data) {
if (self.PromiseState !== 'pending') return
self.PromiseState = 'rejected'
self.PromiseResult = data
// 为了让then()方法变成异步的,需要加定时器
setTimeout(() => {
self.callbacks.forEach((item) => {
item.onRejected(self.PromiseResult);
});
})
}
try {
executor(resolve, reject);
} catch (e) {
reject(e)
}
}