Promise表示一个异步操作的最终结果 , 以之交互的方式主要有then方法 , 该方法主要注册了两个回调函数 , 用于接受Promise的最终结果和不能执行的原因
Promise的状态主要有三种 等待 , 执行 , 拒绝
- 等待pending等待进入执行或拒绝状态
- 执行resolve不能进入其他状态 , 有一个不可变的最终结果
- 拒绝Rejected不能进入其他状态 , 有一个不可变得拒绝原因
Promise.then(onResolve , onRejected) then接受两个参数
- 如果onResolve不是函数 , 其必须被忽略
- 如果onRejected不是函数 , 其必须被忽略
onResolve特性
- promise执行结束后其必须被调用 , 第一个值就是promise的结果
- promise结束前不可以被调用
- onResolve调用次数不可以大于一次
onRejected特性
- promise被拒绝执行后其必须被调用 , 其第一个参数为promise的拒绝原因
- promise结束前不可以被调用
- onRejected调用次数不可以大于一次
- onReslove和onRejected必须被作为函数调用 (即没有this值)
多次调用
- then方法可以被同一个promise调用多次
- 当promise成功执行时 , 所以onResolve需按照其注册顺序依次回调
- 当promise被拒绝执行时 , 所以的onRejected需按照其注册顺序依次回调
返回
- then方法必须返回一个promise对象
实现一个Promise
class Mypromise{
constructor(func){
/* 当前状态
Pending等待
Resolve执行
Rejected拒绝 */
this.status = 'Pending';
// 用户的回调函数
// 队列
this.queueResolve = [];
this.queneRejected = [];
// 用户的回调函数
this._func = func ;
// 用户输入的内容
this._val = null;
}
_myRejected(val){
setTimeout(() => {
// 判断当前的状态是否是等待
if(this.status !== 'Pending') return ;
// 将现在的状态修改成 执行
this.status = 'Resolve';
// 保存当前的数据
this._val = val ;
this.queueResolve.map(call => call(val)) ;
},0)
}
_myResolve(val){
setTimeout(() =>{
// 判断当前的状态是否是等待
if(this.status !== 'Pending') return ;
// 将现在的状态修改成 错误
this.status = 'Rejected';
// 保存当前的数据
this._val = val ;
this.queneRejected.map(call => call(val)) ;
},0)
}
then(resolve , reject){
resolve = typeof resolve === "function" ? resolve : new Function().bind(null);
reject = typeof reject === "function" ? reject : new Function().bind(null)
// let x = this.#func(this.#myRejected , this.#myResolve);
if(this.status === 'Pending'){
this.queueResolve.push(resolve);
this.queneRejected.push(reject);
} else if(this.status === 'Resolve')
this._myResolve(this._func);
else
this._myRejected(this._func);
return
};
}