PromiseA+规范及手写Promise
promise的状态
一个promise有三种状态:等待态(Pending)、执行态(Fullfilled)、拒绝态(Rejected),初始的状态为Pending,可以变更为剩下两种状态种的其中一种,但一旦变更之后,不可再次改变状态
满足A+规范三种状态的情况并状态变更只以第一次为准:
class FackPromise{
// 定义初始状态
private promiseState:string="Pending";
// 定义初始返回结果
private promiseResult:any=null;
constructor(executor:Function){
// 绑定this
this.reslove=this.reslove.bind(this);
this.reject=this.reject.bind(this);
// 执行传递的方法,并透传resolve和reject
executor(this.reslove,this.reject)
}
// 定义reslove方法
reslove(value:any){
// 状态不可逆
if(this.promiseState==='Rejected') return;
this.promiseState='Fulfilled';
this.promiseResult=value;
}
// 定义reject方法
reject(reson:any){
// 状态不可逆
if(this.promiseState==='Fulfilled') return;
this.promiseState='Rejected';
this.promiseResult=reson
}
}
const promiseTest=new FackPromise((resolve:Function,reject:Function)=>{
resolve("成功")
reject("失败")
})
console.log('qy:promiseTest-----',promiseTest);
.then方法
A+规范规定,一个Promise必须有then方法以访问其当前的值、终值和拒因。
-
then方法接受两个参数,onFulfilled是当Promise状态变为Fullfilled的状态的回调,onRejected是当Promise状态变为Rejected的回调,两个参数都必须是函数,并且满足1.promise之前结束前不可调用 。2.调用次数不超过一次。3.值不是函数忽略。
-
返回一个promise方法,下一次then受上一次then返回结果的影响
-
多次调用,onFulfilled,onRejected会按顺序执行
-
then方法是一个微任务
class FackPromise {
// 定义初始状态
private promiseState: string = "Pending";
// 定义初始返回结果
private promiseResult: any = null;
private onFulfilledCallback: any[] = [];
private onRejectedCallback: any[] = [];
constructor(executor: Function) {
// 绑定this
this.reslove = this.reslove.bind(this);
this.reject = this.reject.bind(this);
// 执行传递的方法,并透传resolve和reject
try {
executor(this.reslove, this.reject)
} catch (error) {
this.reject(error)
}
}
// 定义reslove方法
reslove(value: any) {
// 状态不可逆
if (this.promiseState === 'Rejected') return;
this.promiseState = 'Fulfilled';
this.promiseResult = value;
while (this.onFulfilledCallback.length) {
this.onFulfilledCallback.shift()(this.promiseResult)
}
}
// 定义reject方法
reject(reson: any) {
// 状态不可逆
if (this.promiseState === 'Fulfilled') return;
this.promiseState = 'Rejected';
this.promiseResult = reson
while (this.onRejectedCallback.length) {
this.onRejectedCallback.shift()(this.promiseResult)
}
}
then(onFulfilled?: Function, onRejected?: Function) {
// 如果不是函数,忽略
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (val: any) => val;
onRejected = typeof onRejected === 'function' ? onRejected : (reason: any) => { throw reason };
// 。then返回promise
const thenPromise = new FackPromise((resolve: Function, reject: Function) => {
// 支持链式调用
const resolvePromise = (cb: any) => {
setTimeout(()=>{
try {
const x = cb(this.promiseResult)
if (x === thenPromise) {
// 不能返回自身哦
throw new Error('不能返回自身。。。')
}
if (x instanceof FackPromise) {
// 如果返回值是Promise
// 如果返回值是promise对象,返回值为成功,新promise就是成功
// 如果返回值是promise对象,返回值为失败,新promise就是失败
// 谁知道返回的promise是失败成功?只有then知道
x.then(resolve, reject)
} else {
// 非Promise就直接成功
resolve(x)
}
} catch (err) {
// 处理报错
reject(err)
}
})
}
// 只会调用一个
if (this.promiseState === 'Fulfilled') {
resolvePromise(onFulfilled);
} else if (this.promiseState === 'Rejected') {
resolvePromise(onRejected);
} else {
this.onFulfilledCallback.push(resolvePromise.bind(this, onFulfilled));
this.onRejectedCallback.push(resolvePromise.bind(this, onRejected));
}
})
return thenPromise;
}
}
const promiseTest = new FackPromise((resolve: Function, reject: Function) => {
resolve("成功")
reject("失败")
}).then((res: any) => {
console.log('qy:res-----', res);
})
console.log('qy:promiseTest-----', promiseTest);
.all方法
- 遇到非promise当作成功,直到所有的都成功才返回
static all(promises:FackPromise[]){
const result:any[]=[];
let count=0;
return new FackPromise((resolve:Function, reject:Function) => {
const addData=(index:number,value:any)=>{
result[index]=value;
count++;
if(count===promises.length) resolve(result);
}
promises.forEach((promise:FackPromise,index:number)=>{
if(promise instanceof FackPromise){
promise.then((res:any)=>{
addData(index,res);
},(err:any)=>{
reject(err)
})
}else{
addData(index,promise)
}
})
})
}
.race
static race(promises) {
return new MyPromise((resolve, reject) => {
promises.forEach(promise => {
if (promise instanceof MyPromise) {
promise.then(res => {
resolve(res)
}, err => {
reject(err)
})
} else {
resolve(promise)
}
})
})
}
参考
https://juejin.cn/post/6994594642280857630#heading-8