const PENDING = 'pending';
const REJECTED = 'rejected';
const FULFILLED = 'fulfilled'
class MyPromise{
// 执行器
constructor(exector){
try{
exector(this.resolve, this.reject)
}catch(e){
this.rejected(e)
}
}
// 状态
status = PENDING;
// 成功的值
value= undefined;
// 失败的原因
reason = undefined;
// 成功的回调
successCallback = [];
// 失败的回调
filedCallback = [];
resolve = (value) =>{
// 判断当前状态
if(this.status !== PENDING) return;
this.value = value;
this.status = FULFILLED;
// 如果是异步的需要将异步的函数执行
this.successCallback.forEach(item => item(this.value))
};
// 定义为箭头函数 不改变函数内的this
reject = (reason) =>{
// 判断当前状态
if(this.status !== PENDING) return;
this.reason = reason;
this.status = REJECTED;
// 如果是异步的需要将异步的函数执行
this.filedCallback.forEach(item => item(this.reason))
};
then(successCallback, failCallback) {
// 判断是否传入了成功和失败回调
successCallback = successCallback ? successCallback : value => value;
failCallback = failCallback ? failCallback : value => value;
// 返回的是个Promise
let promise = new MyPromise((resolve, reject)=>{
// 判断状态
if(this.status = FULFILLED) {
// 成功的状态
// 为了可以获得prmise的值,判断是否返回的是自己
setTimeout(() => {
try {
let x = successCallback(this.value);
resolvePromise(promise, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0)
//
} else if(this.status = REJECTED) {
// 失败的状态
setTimeout(() => {
try {
let x = failCallback(this.reason);
resolvePromise(promise, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0)
} else {
// 进行中的状态
// 异步函数放入对应得数组内,当状态改变时执行
this.successCallback.push(() => {
setTimeout(() => {
try {
let x = successCallback(this.value);
resolvePromise(promise, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0)
});
this.filedCallback.push(() => {
setTimeout(() => {
try {
let x = failCallback(this.reason);
resolvePromise(promise, x, resolve, reject)
} catch (error) {
reject(error)
}
}, 0)
})
}
})
return promise;
}
finally(callback) {
return this.then(value => {
return MyPromise.resolve(callback()).then(() => value)
}, reason => {
return MyPromise.resolve(callback()).then(() => { throw reason})
})
}
catch(failCallback) {
return this.then(undefined, failCallback)
}
static all(arr) {
let result =[];
index = 0;
return new MyPromise((resolve, reject) => {
function addData(key, value) {
result[key] = value;
index++;
if (index === arr.length) {
resolve(result)
}
}
for(let i = 0; i <arr.length; i ++) {
let current = arr[i];
if (current instanceof MyPromise) {
current.then(value => addData(i, value), reason => reject(reason))
} else {
addData(i, arr[i])
}
}
})
}
static resolve(value) {
if (value instanceof MyPromise) return value;
return new MyPromise(resolve => resolve(value));
}
}
function resolvePromise(promise, x, resolve, reject) {
if (promise === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
if (x instanceof MyPromise) {
x.then(resolve, reject)
} else {
resolve(x);
}
}
ES6 Promise
最新推荐文章于 2024-11-01 13:37:40 发布