手写Promise
用于理解promise原理
function Promise(executor) {
//初始化Promise状态为pending
this.PromiseState = "pending";
//初始化返回结果为Null
this.PromiseResult = null;
//初始化回调数组
this.callBacks = [];
//保存当前this
const that = this;
//编写reslove函数
function reslove(data) {
if(that.PromiseState === "pending") {
that.PromiseState = "fulfilled";
that.PromiseResult = data;
setTimeout(()=>{
that.callBacks.forEach(item => {
item.onResolved(data);
})
})
}
}
//编写reject函数
function reject(data) {
if(that.PromiseState === "pending") {
that.PromiseState = "rejected";
that.PromiseResult = data;
setTimeout(()=>{
that.callBacks.forEach(item => {
item.onRejected(data);
})
})
}
}
try {
executor(reslove,reject);
} catch(e) {
reject(e);
}
}
//添加then函数
Promise.prototype.then = function(onResolved, onRejected) {
const that = this;
//判断回调函数参数
if(typeof onRejected !== 'function') {
onRejected = reason => {
throw reason;
}
}
//值传递
if(typeof onResolved !== 'function') {
onResolved = value => value;
}
//返回一个Promise
return new Promise((resolve, reject) => {
//封装函数
function callback(type) {
//出错直接reject结束函数
try {
//获取返回的数据
let result = type(that.PromiseResult);
//判断数据的类型是否为Promise
if(result instanceof Promise) {
result.then(v => {
resolve(v);
}, r => {
reject(r);
})
} else {
//如果不为Promise,直接返回一个fulfilled状态的promise
resolve(result);
}
} catch(e) {
reject(e);
}
}
//判断fulfilled状态
if(this.PromiseState === "fulfilled") {
setTimeout(()=>{
callback(onResolved);
})
}
//判断rejected状态
if(this.PromiseState === "rejected") {
setTimeout(() => {
callback(onRejected);
});
}
//判断pending状态
if(this.PromiseState === "pending") {
this.callBacks.push({
onResolved:function() {
callback(onResolved);
},
onRejected:function() {
onRejected(that.PromiseResult);
}
})
}
})
}
//添加catch方法
Promise.prototype.catch = (onRejected) => {
return this.then(undefined, onRejected);
}
//添加resolve方法
Promise.resolve = function(value) {
return new Promise((resolve, reject) => {
if(value instanceof Promise) {
value.then(v=>{
resolve(v);
}, r=>{
reject(r);
})
} else {
resolve(value);
}
});
}
//添加reject方法
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++) {
count++;
arr.push(v);
promises[i].then((v)=>{
if(count === promises.length) {
resolve();
}
},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);
})
}
})
}