1. 明确需求
一个 Promise 应该具备的最基本的特征,至少有以下几点:
- 可以接收一个 executor 作为入参
- 具备 pending、resolved 和 rejected 这三种状态
2. 代码编写
1. 基本轮廓
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise1(execute) {
// 保存this
let self = this
// status记录当前状态,设置默认状态为pending
self.status = PENDING
// resolve的值
self.value = null
// reject的值
self.reason = null
function resolve(value) {
if (self.status === PENDING) {
// 保存resolve的值
self.value = value
// 切换状态 resolved
self.status = FULFILLED
}
}
function reject(value) {
if (self.status === PENDING) {
// 保存reject的值
self.reason = value
// 切换状态 rejected
self.status = REJECTED
}
}
// 把 resolve 和 reject 能力赋予执行器
try{
execute(resolve, reject)
}catch(e){
reject(e)
}
}
2. then方法的行为
每一个 promise 实例一定有个 then 方法,由此我们不难想到,then 方法应该装在 Promise 构造函数的原型对象上
Promise1.prototype.then = function (onFulfilled, onRejected) {
let self = this
// 注意,onResolved 和 onRejected必须是函数;如果不是,我们此处用一个透传来兜底
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
if (self.status === FULFILLED) {
// 若是fulfilled状态,则执行fulfilled对应方法
onFulfilled(self.value)
} else if (self.status === REJECTED) {
// 若是 rejected 状态,则执行 rejected 对应方法
onRejected(self.reason);
}
}
3. 运行
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise1(execute) {
// 保存this
let self = this
// status记录当前状态,设置默认状态为pending
self.status = PENDING
// resolve的值
self.value = null
// reject的值
self.reason = null
function resolve(value) {
if (self.status === PENDING) {
// 保存resolve的值
self.value = value
// 切换状态 resolved
self.status = FULFILLED
}
}
function reject(value) {
if (self.status === PENDING) {
// 保存reject的值
self.reason = value
// 切换状态 rejected
self.status = REJECTED
}
}
// 把 resolve 和 reject 能力赋予执行器
try{
execute(resolve, reject)
}catch(e){
reject(e)
}
}
Promise1.prototype.then = function (onFulfilled, onRejected) {
let self = this
// 注意,onResolved 和 onRejected必须是函数;如果不是,我们此处用一个透传来兜底
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
if (self.status === FULFILLED) {
// 若是fulfilled状态,则执行fulfilled对应方法
onFulfilled(self.value)
} else if (self.status === REJECTED) {
// 若是 rejected 状态,则执行 rejected 对应方法
onRejected(self.reason);
}
}
new Promise1((resolve, reject) => {
resolve('成功了')
}).then(value => {
console.log('1', value)
}, (reason) => {
console.log('2', reason)
})
new Promise1(function (resolve, reject) {
reject('错了!');
}).then(function (value) {
console.log('3', value);
}, function (reason) {
console.log('4', reason);
});
打印结果