一、Promise特点
1、创建Promise对象时候,必须给它的参数传入一个函数,否则会报错,那么如何判断传进来的参数是一个函数呢?
function _isFunction(hander) { let result = typeof hander == 'function'; //方法1 //let result = hander.constructor.name == 'Function'; //方法2 return result; }
2、创建Promise对象的时候,传入的参数是一个带有二个参数的回调函数,且立即执行。
handle(this._resolve.bind(this), this._reject.bind(this));
function _resolve(){}
function _reject(){}
由于在构造函数中调用函数,函数中的this不是指创建promise对象中的this,所以必须在构造函数中的handle中改变this的指向
3、刚创建的Promise对象是的状态是处于pending
// 定义常量保存对象的状态
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
this.status = PENDING;
4、一旦我们在Promise对象中调用回调函数,则状态不可匿更改
function _resolve(value){
// 这里是为了防止重复修改
if(this.status === PENDING){
this.status = FULFILLED;
}
}
function _reject(reason){
// 这里是为了防止重复修改
if(this.status === PENDING) {
this.status = REJECTED;
}
}
5、通过then方法来监听状态的改变,以及下一步执行的函数
5.1 如果添加监听时状态已经改变, 立即执行监听的回调
5.2如果添加监听时状态还未改变, 那么状态改变时候再执行监听回到
5.3 同一个Promise对象可以添加多个then监听, 状态改变时所有的监听按照添加顺序执行
then(onResolved, onRejected){
// 1.判断有没有传入成功的回调
if(this._isFunction(onResolved)){
// 2.判断当前的状态是否是成功状态
if(this.status === FULFILLED){
onResolved(this.value);
}
}
// 1.判断有没有传入失败的回调
if(this._isFunction(onRejected)){
// 2.判断当前的状态是否是失败状态
if(this.status === REJECTED){
onRejected(this.reason);
}
}
// 2.判断当前的状态是否是默认状态
if(this.status === PENDING){
if(this._isFunction(onResolved)){
// this.onResolvedCallback = onResolved;
this.onResolvedCallbacks.push(onResolved);
}
if(this._isFunction(onRejected)){
// this.onRejectedCallback = onRejected;
this.onRejectedCallbacks.push(onRejected);
}
}
}
二:总的代码
// 定义常量保存对象的状态 const PENDING = "pending"; const FULFILLED = "fulfilled"; const REJECTED = "rejected"; class MyPromise{ constructor(hander) { // 0、初始化状态 this.status = PENDING; this.value = null; this.reason = null; this.onResolveCallBack = null; this.onRejectCallBack = null; // 1、判断传进来的参数是否为函数 if(!this.isFunction(hander)){ throw new Error("请传入一个参数"); } hander(this._resolve.bind(this),this._reject.bind(this)); } then(onResolve,onRejected) { if(this.isFunction(onResolve)) { //防止状态被更改 if(this.status == FULFILLED){ onResolve(this.value); } } if(this.isFunction(onRejected)) { ////防止状态被更改 if(this.status == REJECTED){ onRejected(this.reason); } } //默认状态 if(this.status == PENDING){ if(this.isFunction(onResolve)){ this.onResolvedCallback = onResolve; } if(this.isFunction(onRejected)){ this.onResolvedCallback = onRejected; } } } //2、FULFILLED状态执行的函数 _resolve(value){ if(this.status == PENDING){ this.status = FULFILLED; this.value = value; // this.onResolveCallBack&&this.onResolveCallBack(this.value); //这个是为了当状态还没发生更改的时候执行的 } } //3、REJECTED状态执行的函数 _reject(reason){ if(this.status == PENDING){ this.status = REJECTED; this.reason = reason; this.onResolveCallBack&&this.onResolveCallBack(this.reason); } } isFunction(fn){ return typeof fn == 'function'; } }