1. Promise 是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行
2. Promise 会有三种状态
Pending 等待
Fulfilled 完成
Rejected 失败
3. 状态只能由 Pending --> Fulfilled 或者 Pending --> Rejected,且一但发生改变便不可二次修改;
4. Promise 中使用 resolve 和 reject 两个函数来更改状态;
5. then 方法内部做但事情就是状态判断
如果状态是成功,调用成功回调函数
如果状态是失败,调用失败回调函数
-
executor 立即执行 传入定时器,resolve隔2s 后执行
解决:onFulfilledCallback 数组先储存起来,等resolve执行时,在执行数组
-
链式调用
解决: then 方法返回一个MyPromise对象
-
then 传入函数,返回值可能也是一个MyPromise对象
解决: resolvePromise 方法
-
executor传入定时器 + then 的链式调用
解决: nextPromise,先返回一个MyPromise对象,状态pending,等resolve执行时 MyPromise对象的resolve才执行即resolvePromise 方法
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING;
// 成功之后的值
value = null;
// 失败之后的原因
reason = null;
// 链式调用 状态是pending 的nextPromise对象
nextPromise = null;
resolve = (value) => {
if (this.status === PENDING) {
// 状态修改为成功
this.status = FULFILLED;
// 保存成功之后的值
this.value = value;
while (this.onFulfilledCallback.length) {
const result = this.onFulfilledCallback.shift()(value)
if (this.nextPromise) { resolvePromise(result, this.nextPromise.resolve, this.nextPromise.reject)
}
}
}
}
reject = (reason) => {
if (this.status === PENDING) {
// 状态成功为失败
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
while (this.onRejectedCallback.length) {
this.onRejectedCallback.shift()(value)
}
}
}
// 存储成功回调函数
onFulfilledCallback = []
// 存储失败回调函数
onRejectedCallback = []
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
// 调用成功回调,并且把值返回
const result = onFulfilled(this.value);
return new MyPromise((reslove, reject) => {
resolvePromise(result, reslove, reject)
})
} else if (this.status === REJECTED) {
// 调用失败回调,并且把原因返回
const result = onRejected(this.reason);
return new MyPromise((reslove, reject) => {
reject(result)
})
} else {
if (onFulfilled) { this.onFulfilledCallback.push(onFulfilled)
}
if (onFulfilled) { this.onRejectedCallback.push(onRejected)
}
this.nextPromise = new MyPromise((reslove, reject) => {})
return this.nextPromise
}
}
}
function resolvePromise(x, resolve, reject) {
// 判断x是不是 MyPromise 实例对象
if(x instanceof MyPromise) {
// 执行 x,调用 then 方法,目的是将其状态变为 fulfilled 或者 rejected
// x.then(value => resolve(value), reason => reject(reason))
// 简化之后
x.then(resolve, reject)
} else{
// 普通值
resolve(x)
}
}
// 调用
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 2000);
})
promise.then(value => {
console.log(1)
console.log('resolve', value)
return '99'
}).then(res => {
console.log(res)
});
// promise.then(value => {
// console.log(2)
// console.log('resolve', value)
// })
// promise.then(value => {
// console.log(3)
// console.log('resolve', value)
// })