// 声明构造函数
function Promise(executor) {
// 设置初始状态和值
this.PromiseState = 'pending';
this.PromiseResult = undefined;
// 回调函数的属性
this.callbacks = [];
let _this = this;
// reslove函数声明
function res(data) {
// 让状态只能被修改一次
if (_this.PromiseState !== 'pending') return;
// 1 修改对象的状态 (PromiseState)
_this.PromiseState = 'fulfiled';
// 2 设置对象的结果 (PromiseResult)
_this.PromiseResult = data;
// 状态改变时 调用成功状态的会回调函数
setTimeout(() => {
_this.callbacks.forEach((item) => {
// 调用成功状态的回调函数
item.onResolve(data)
})
})
}
// reject函数声明
function rej(data) {
// 让状态只能被修改一次
if (_this.PromiseState !== 'pending') return;
// 1 修改对象的状态 (PromiseState)
_this.PromiseState = 'rejected';
// 2 设置对象的结果 (PromiseResult)
_this.PromiseResult = data;
// 状态改变时 调用失败状态的回调函数
setTimeout(() => {
_this.callbacks.forEach((item) => {
item.onReject(data)
})
})
}
// 抛出异常改变状态时调用
try {
// 同步调用[执行器函数]
executor(res, rej);
} catch (e) {
// console.log(e);
rej(e);
}
}
// 原型链上添加.then方法
Promise.prototype.then = function (onResolve, onReject) {
const self = this;
// then方法的值传递 (未传入onResolve回调函数)
if (typeof onResolve !== 'function') {
onResolve = value => value;
}
// catch的异常穿透 (未传入onReject回调函数)
if (typeof onReject !== 'function') {
onReject = (resaon) => {
throw resaon;
}
}
// then方法的返回状态
return new Promise((resolve, reject) => {
// 封装回调函数
function callback(type) {
// 抛出异常
try {
// 获取回调函数的返回结果
// onResolve(this.PromiseResult);
let result = type(self.PromiseResult);
// 判断回答调函数返回结果的类型
if (result instanceof Promise) {
// 返回的是一个Promise
result.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
// 返回成功的状态
resolve(result);
}
} catch (e) {
reject(e);
}
}
// 状态改变之后 调用回调函数
if (this.PromiseState === 'fulfiled') {
setTimeout(() => {
callback(onResolve);
})
}
if (this.PromiseState === 'rejected') {
setTimeout(() => {
callback(onReject);
})
}
// 执行异步任务时,状态为pending的判断
if (this.PromiseState === 'pending') {
// 保存回调函数
this.callbacks.push({
onResolve: function () {
callback(onResolve)
},
onReject: function () {
callback(onReject)
}
})
}
});
}
// 原型链上添加.catch方法
Promise.prototype.catch = function (onReject) {
return this.then(undefined, onReject)
}
// 封装resolve方法
Promise.resolve = function (value) {
// 返回一个Promise 对象
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
resolve(value);
}
})
}
// 封装resject方法
Promise.reject = function (reason) {
return new Promise((resolve, reject) => {
reject(reason);
})
}
// 添加all方法
Promise.all = function (promises) {
return new Promise((resolve, reject) => {
let count = 0;
let arr = [];
// 遍历
for (let i = 0; i < promises.length; i++) {
promies[i].then(v => {
count++;
arr[i] = v;
if (count === promises.length) {
resolve(arr)
}
}, r => {
reject(r);
})
}
})
}
// 添加race方法
Promise.race = function (promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
resolve(v)
}, r => {
reject(r)
})
}
})
}