手写promise,首先要确认好promise的状态,主要有三种:pending、filfulled、rejected,其次是定义好filfulled的返回值value跟rejected的返回值reason,然后是resolve跟reject方法实现status改变及返回值更新,最后是then的实现,为promise的回调。
注意:对于异步事件使用事件订阅发布实现监听
1、class实现
//实现promise
class _promise{
constructor(excutor){
var self = this;
this.status = 'pending';
this.value = null;
this.reason = null;
//事件缓存列表
this.onFilfulledFns = []
this.onRejectedFns = []
//resolve
function resolve(value){
if(self.status === 'pending'){
self.value = value;
self.status = 'filfulled';
//事件发布
self.onFilfulledFns.forEach(fn => fn(value))
}
}
//reject
function reject(reason){
if(self.status === 'pending'){
self.value = reason;
self.status = 'rejected';
//事件发布
self.onRejectedFns.forEach(fn => fn(reason))
}
}
//执行器
try{
excutor(resolve,reject)
}catch(err){
this.reject(err)
}
}
//then
then(onFilfulled,onRejected){
if(this.status === 'pending'){
//事件订阅
this.onFilfulledFns.push(onFilfulled);
this.onRejectedFns.push(onRejected)
}else if(this.status === 'filfulled'){
onFilfulled(this.value)
}else{
onRejected(this.reason)
}
}
}
2、函数实现
//实现promise
function _promise(excutor){
let self = this;
this.status = 'pending';
this.value = null;
this.reason = null;
//事件缓存
this.fulfilledFns = [];
this.rejectedFns = [];
function resolve(value){
if(self.status === 'pending'){
self.value = value;
self.status = 'fulfilled';
//事件发布
self.fulfilledFns.forEach(fn => fn(value))
}
}
function reject(reason){
if(self.status === 'pending'){
self.reason = reason;
self.status = 'rejected';
//事件发布
self.rejectedFns.forEach(fn => fn(reason))
}
}
//执行器
try{
excutor(resolve,reject)
}
catch(err){
reject(err)
}
}
//then
_promise.prototype.then = function(onFulfilled,onRejected){
//异步事件订阅
if(this.status === 'pending'){
this.fulfilledFns.push(onFulfilled)
this.rejectedFns.push(onRejected)
}else if(this.status === 'fulfilled'){
onFulfilled(this.value)
}else{
onRejected(this.reason)
}
}
上述两种写法为简单实现,后续持续优化,Promose.all、Promise.allSettled、Promise.race请参考我的其他文章