//https://juejin.cn/post/6945319439772434469
//手写promise
//传入执行器 执行器立马执行
//有pending | fulfilled | rejected三种状态 且只能 pending -> fulfilled | pend -> rejected
//由 resolve | reject 在 pending时去改变状态
//then中根据状态判断执行resolve | reject 的回调
//定义三种状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// if(this.status === FULFILLED) {
// onFulfilled(this.value);
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// }
// }
// }
// const promise = new MyPromise((resolve, reject) => {
// resolve('this is resolve');
// reject('this is rejected')
// })
// promise.then(res => {
// console.log(res)
// })
//实现最基本的resolve reject then 测试异步问题
// const promise = new MyPromise((resolve, reject) => {
// setTimeout(() => {
// resolve('this is resolve')
// }, 2000)
// })
// promise.then(res => {
// console.log(res)
// })
//测试不通过 因为setTimeout是下一轮宏任务 在这之前会先执行then 但是status一直是pendding 所以就会停止不执行后面的 需要对pending状态进行完善
//在pendding的时候如果进入了then 则先缓存对应的回调 等到状态改变后再执行
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调
// onFulfilledCallback = null;
// onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// this.onRejectedCallback && this.onRejectedCallback(this.reason)
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// if(this.status === FULFILLED) {
// onFulfilled(this.value);
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {//pending的情况
// this.onFulfilledCallback = onFulfilled;
// this.onRejectedCallback = onRejected;
// }
// }
// }
// //再次测试异步执行功能 成功执行异步功能
// const promise = new MyPromise((resolve, reject) => {
// setTimeout(()=> resolve('this is resolve'), 1000)
// })
// promise.then(res => {
// console.log(res) }
// )
// //测试多次then
// promise.then(res => {
// console.log(2)
// console.log(res)
// })
// promise.then(res => {
// console.log(3)
// })
//测试失败 只有最后一个then执行 因为缓存resolve | reject操作的变量会被替代成最后一次then 所以应该使用数组缓存
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// if(this.status === FULFILLED) {
// onFulfilled(this.value);
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {//pending的情况
// // this.onFulfilledCallback = onFulfilled;
// // this.onRejectedCallback = onRejected;
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected)
// }
// }
// }
//再次测试异步执行功能 成功执行异步功能
// const promise = new MyPromise((resolve, reject) => {
// setTimeout(()=> resolve('this is resolve'), 1000)
// })
// promise.then(res => {
// console.log(res) }
// )
// //测试多次then
// promise.then(res => {
// console.log(2)
// console.log(res)
// })
// promise.then(res => {
// console.log(3)
// })
//成功执行测试链式调用的功能
// const promise = new MyPromise((resolve, reject) => {
// // 目前这里只处理同步的问题
// resolve('success')
// })
// function other () {
// return new MyPromise((resolve, reject) =>{
// resolve('other')
// })
// }
// promise.then(value => {
// console.log(1)
// console.log('resolve', value)
// return other()
// }).then(value => {
// console.log(2)
// console.log('resolve', value)
// })
//链式调用失败 因为then并没有返回啥 所以应该在then后返回promoise
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// //then里面应该返回promise
// const nextPronmise = new MyPromise((resolve, reject) => {
// //这里的内容在执行器 会立即执行
// if(this.status === FULFILLED) {
// //获取成功回调函数的执行结果
// const x = onFulfilled(this.value);
// //传入resolvePromise集体处理
// resolvePromise(x, resolve, reject);
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected);
// }
// })
// return nextPronmise;
// }
// }
// function resolvePromise(x, resolve, reject) {
// //判断x是不是MyPromise实例
// if(x instanceof MyPromise) {
// x.then(resolve, reject)
// } else {
// resolve(x)
// }
// }
//重新测试链式调用
// const promise = new MyPromise((resolve, reject) => {
// // 目前这里只处理同步的问题
// resolve('success')
// })
// function other () {
// return new MyPromise((resolve, reject) =>{
// resolve('other')
// })
// }
// promise.then(value => {
// console.log(1)
// console.log('resolve', value)
// return other()
// }).then(value => {
// console.log(2)
// console.log('resolve', value)
// })
//测试成功 可以链式调用 接下来添加判断promise是否是自身(如果then返回自己的promise对象 会陷入循环调用报错)
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// //then里面应该返回promise
// const nextPronmise = new MyPromise((resolve, reject) => {
// //这里的内容在执行器 会立即执行
// if(this.status === FULFILLED) {
// //获取成功回调函数的执行结果
// const x = onFulfilled(this.value);
// //传入resolvePromise集体处理 传入自身才能判断
// resolvePromise(nextPromise, x, resolve, reject);
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected);
// }
// })
// return nextPronmise;
// }
// }
// function resolvePromise(nextPromise, x, resolve, reject) {
// //如果是自身的promise 则直接报错
// if(nextPromise === x) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
// //判断x是不是MyPromise实例
// if(x instanceof MyPromise) {
// x.then(resolve, reject)
// } else {
// resolve(x)
// }
// }
// test.js
// const promise = new MyPromise((resolve, reject) => {
// resolve(100)
// })
// const p1 = promise.then(value => {
// console.log(value)
// return p1
// })
// "Uncaught ReferenceError: Cannot access 'p1' before initialization"会报错 因为我们必须等待nextPromise初始化完成
//所以必须创建一个微任务等待nextPromise初始化完成
// class MyPromise {
// constructor(excutor) {
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// //then里面应该返回promise
// const nextPronmise = new MyPromise((resolve, reject) => {
// //这里的内容在执行器 会立即执行
// if(this.status === FULFILLED) {
// //创建一个微任务并等待promise完成
// queueMicrotask(() => {
// //获取成功回调函数的执行结果
// const x = onFulfilled(this.value);
// //传入resolvePromise集体处理 传入自身才能判断
// resolvePromise(nextPromise, x, resolve, reject);
// })
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected);
// }
// })
// return nextPronmise;
// }
// }
// function resolvePromise(nextPromise, x, resolve, reject) {
// //如果是自身的promise 则直接报错
// if(nextPromise === x) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
// //判断x是不是MyPromise实例
// if(x instanceof MyPromise) {
// x.then(resolve, reject)
// } else {
// resolve(x)
// }
// }
// const promise = new MyPromise((resolve, reject) => {
// resolve('success')
// })
// // 这个时候将promise定义一个p1,然后返回的时候返回p1这个promise
// const p1 = promise.then(value => {
// console.log(1)
// console.log('resolve', value)
// return p1
// })
// // 运行的时候会走reject
// p1.then(value => {
// console.log(2)
// console.log('resolve', value)
// }, reason => {
// console.log(3)
// console.log(reason.message)
// })
//接下来开始进行错误捕捉 即如果执行器有错误 则promise变为reject
// class MyPromise {
// constructor(excutor) {
// try{
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// } catch(err) {
// this.reject(err)
// }
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// //then里面应该返回promise
// const nextPronmise = new MyPromise((resolve, reject) => {
// //这里的内容在执行器 会立即执行
// if(this.status === FULFILLED) {
// //创建一个微任务并等待promise完成
// queueMicrotask(() => {
// //获取成功回调函数的执行结果
// const x = onFulfilled(this.value);
// //传入resolvePromise集体处理 传入自身才能判断
// resolvePromise(nextPromise, x, resolve, reject);
// })
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected);
// }
// })
// return nextPronmise;
// }
// }
// function resolvePromise(nextPromise, x, resolve, reject) {
// //如果是自身的promise 则直接报错
// if(nextPromise === x) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
// //判断x是不是MyPromise实例
// if(x instanceof MyPromise) {
// x.then(resolve, reject)
// } else {
// resolve(x)
// }
// }
// //验证一下 成功捕获
// const promise = new MyPromise((resolve, reject) => {
// // resolve('success')
// throw new Error('执行器错误')
// })
// promise.then(value => {
// console.log(1)
// console.log('resolve', value)
// }, reason => {
// console.log(2)
// console.log(reason.message)
// })
//如果在then中发生错误 也应该同样 使用trycatch
// class MyPromise {
// constructor(excutor) {
// try{
// excutor(this.resolve, this.reject);//立即执行 new Promise(() => {}, () => {})
// } catch(err) {
// this.reject(err)
// }
// }
// status = PENDING;//状态默认为pendding
// value = null;//resolve的参数
// reason = null;//reject的参数
// //保存成功或者失败的回调数组
// onFulfilledCallbacks = [];
// onRejectedCallbacks = [];
// // onFulfilledCallback = null;
// // onRejectedCallback = null;
// //resolve
// resolve = (value) => {
// if(this.status === PENDING) {
// this.status = FULFILLED;
// this.value = value;
// //执行缓存的回调 因为then已经先执行了 resolve是之后执行的
// // this.onFulfilledCallback && this.onFulfilledCallback(this.value)
// while(this.onFulfilledCallbacks.length) {
// this.onFulfilledCallbacks.shift()(this.value)
// }
// }
// }
// //reject
// reject = (reason) => {
// if(this.status === PENDING) {
// this.status = REJECTED;
// this.reason = reason;
// // this.onRejectedCallback && this.onRejectedCallback(this.reason)
// while(this.onRejectedCallbacks.length) {
// this.onRejectedCallbacks.shift()(this.value)
// }
// }
// }
// then(onFulfilled, onRejected) { //then((value) => {}, (reason) => {})
// //then里面应该返回promise
// const nextPronmise = new MyPromise((resolve, reject) => {
// //这里的内容在执行器 会立即执行
// if(this.status === FULFILLED) {
// //创建一个微任务并等待promise完成
// queueMicrotask(() => {
// //获取成功回调函数的执行结果
// try {
// const x = onFulfilled(this.value);
// //传入resolvePromise集体处理 传入自身才能判断
// resolvePromise(nextPromise, x, resolve, reject);
// } catch (err) {
// this.reject(err)
// }
// })
// } else if(this.status === REJECTED) {
// onRejected(this.reason)
// } else {
// this.onFulfilledCallbacks.push(onFulfilled);
// this.onRejectedCallbacks.push(onRejected);
// }
// })
// return nextPronmise;
// }
// }
// function resolvePromise(nextPromise, x, resolve, reject) {
// //如果是自身的promise 则直接报错
// if(nextPromise === x) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
// //判断x是不是MyPromise实例
// if(x instanceof MyPromise) {
// x.then(resolve, reject)
// } else {
// resolve(x)
// }
// }
// //验证一下 成功捕获
// const promise = new MyPromise((resolve, reject) => {
// resolve('success')
// // throw new Error('执行器错误')
// })
// // 第一个then方法中的错误要在第二个then方法中捕获到
// promise.then(value => {
// console.log(1)
// console.log('resolve', value)
// throw new Error('then error')
// }, reason => {
// console.log(2)
// console.log(reason.message)
// }).then(value => {
// console.log(3)
// console.log(value);
// }, reason => {
// console.log(4)
// console.log(reason.message)
// })
//最终代码
// MyPromise.js
// 先定义三个常量表示状态
// const PENDING = 'pending';
// const FULFILLED = 'fulfilled';
// const REJECTED = 'rejected';
// 新建 MyPromise 类
class MyPromise {
constructor(executor){
// executor 是一个执行器,进入会立即执行
// 并传入resolve和reject方法
try {
executor(this.resolve, this.reject)
} catch (error) {
this.reject(error)
}
}
// 储存状态的变量,初始值是 pending
status = PENDING;
// 成功之后的值
value = null;
// 失败之后的原因
reason = null;
// 存储成功回调函数
onFulfilledCallbacks = [];
// 存储失败回调函数
onRejectedCallbacks = [];
// 更改成功后的状态
resolve = (value) => {
// 只有状态是等待,才执行状态修改
if (this.status === PENDING) {
// 状态修改为成功
this.status = FULFILLED;
// 保存成功之后的值
this.value = value;
// resolve里面将所有成功的回调拿出来执行
while (this.onFulfilledCallbacks.length) {
// Array.shift() 取出数组第一个元素,然后()调用,shift不是纯函数,取出后,数组将失去该元素,直到数组为空
this.onFulfilledCallbacks.shift()(value)
}
}
}
// 更改失败后的状态
reject = (reason) => {
// 只有状态是等待,才执行状态修改
if (this.status === PENDING) {
// 状态成功为失败
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
// resolve里面将所有失败的回调拿出来执行
while (this.onRejectedCallbacks.length) {
this.onRejectedCallbacks.shift()(reason)
}
}
}
then(onFulfilled, onRejected) {
const realOnFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
const realOnRejected = typeof onRejected === 'function' ? onRejected : reason => {throw reason};
// 为了链式调用这里直接创建一个 MyPromise,并在后面 return 出去
const promise2 = new MyPromise((resolve, reject) => {
const fulfilledMicrotask = () => {
// 创建一个微任务等待 promise2 完成初始化
queueMicrotask(() => {
try {
// 获取成功回调函数的执行结果
const x = realOnFulfilled(this.value);
// 传入 resolvePromise 集中处理
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error)
}
})
}
const rejectedMicrotask = () => {
// 创建一个微任务等待 promise2 完成初始化
queueMicrotask(() => {
try {
// 调用失败回调,并且把原因返回
const x = realOnRejected(this.reason);
// 传入 resolvePromise 集中处理
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error)
}
})
}
// 判断状态
if (this.status === FULFILLED) {
fulfilledMicrotask()
} else if (this.status === REJECTED) {
rejectedMicrotask()
} else if (this.status === PENDING) {
// 等待
// 因为不知道后面状态的变化情况,所以将成功回调和失败回调存储起来
// 等到执行成功失败函数的时候再传递
this.onFulfilledCallbacks.push(fulfilledMicrotask);
this.onRejectedCallbacks.push(rejectedMicrotask);
}
})
return promise2;
}
// resolve 静态方法
static resolve (parameter) {
// 如果传入 MyPromise 就直接返回
if (parameter instanceof MyPromise) {
return parameter;
}
// 转成常规方式
return new MyPromise(resolve => {
resolve(parameter);
});
}
// reject 静态方法
static reject (reason) {
return new MyPromise((resolve, reject) => {
reject(reason);
});
}
}
function resolvePromise(promise2, x, resolve, reject) {
// 如果相等了,说明return的是自己,抛出类型错误并返回
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
// 判断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)
}
}
MyPromise.resolve().then(() => {
console.log(0);
return MyPromise.resolve(4);
}).then((res) => {
console.log(res)
})
MyPromise.resolve().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() =>{
console.log(6);
})
console