文章目录
Promise是一门新的技术(ES6规范),是JS中进行异步编程的新解决方案(旧方案是单纯使用回调函数)。
温习Promise基础可以看看这篇文章:Promise从入门到精通,小白必看
Promise的基本用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise手写</title>
<script src="./promise.js"></script>
</head>
<body>
<script>
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("OK");
reject("Eror");
})
});
p1.then(value => {
console.log(value);
}, reason => {
console.warn(reason);
});
console.log(Promise.resolve('OK'));
</script>
</body>
</html>
手写 Promise的总体框架
手写Promise
Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)
class Promise{
//构造方法
constructor(executor){
//添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
//声明属性
this.callbacks = [];
//保存实例对象的 this 的值
const self = this;// self _this that
//resolve 函数
function resolve(data){
//判断状态
if(self.PromiseState !== 'pending') return;
//1. 修改对象的状态 (promiseState)
self.PromiseState = 'fulfilled';// resolved
//2. 设置对象结果值 (promiseResult)
self.PromiseResult = data;
//调用成功的回调函数
setTimeout(() => {//回调函数要异步执行
self.callbacks.forEach(item => {
item.onResolved(data);
});
});
}
//reject 函数
function reject(data){
//判断状态
if(self.PromiseState !== 'pending') return;
//1. 修改对象的状态 (promiseState)
self.PromiseState = 'rejected';//
//2. 设置对象结果值 (promiseResult)
self.PromiseResult = data;
//执行失败的回调
setTimeout(() => {//回调函数要异步执行
self.callbacks.forEach(item => {
item.onRejected(data);
});
});
}
try{
//同步调用『执行器函数』
executor(resolve, reject);
}catch(e){
//修改 promise 对象状态为『失败』
reject(e);
}
}
//then 方法封装
then(onResolved,onRejected){//即Promise.prototype.then = function(onResolved, onRejected){}
const self = this;
//判断回调函数参数
if(typeof onRejected !== 'function'){//promise的then链式调用时省略reason => {throw reason}时抛出进行异常穿透,扔到最后catch()处理
onRejected = reason => {
throw reason;
}
}
if(typeof onResolved !== 'function'){
onResolved = value => value;//等同于value => { return value};
}
return new Promise((resolve, reject) => {
//封装函数callback以便下面复用
function callback(type){
try{
//获取回调函数的执行结果
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);
}
}
//调用回调函数 PromiseState
if(this.PromiseState === 'fulfilled'){
setTimeout(() => {//回调函数要异步执行
callback(onResolved);
});
}
if(this.PromiseState === 'rejected'){
setTimeout(() => {//回调函数要异步执行
callback(onRejected);
});
}
//判断 pending 状态
if(this.PromiseState === 'pending'){//当Promise是setInterval异步使用时,状态还没来得及改变,还是初始的pending
//保存回调函数
this.callbacks.push({
onResolved: function(){
callback(onResolved);
},
onRejected: function(){
callback(onRejected);
}
});
}
})
}
//catch 方法
catch(onRejected){
return this.then(undefined, onRejected);
}
//添加 resolve 方法
static resolve(value){//resolve不属于实例对象,属于类,所以前面加个static
//返回promise对象
return new Promise((resolve, reject) => {
if(value instanceof Promise){//如果是Promise类型,你成功我也成功,你失败我也失败
value.then(v=>{
resolve(v);
}, r=>{
reject(r);
})
}else{
//状态设置为成功
resolve(value);
}
});
}
//添加 reject 方法
static reject(reason){
return new Promise((resolve, reject)=>{
reject(reason);
});
}
//添加 all 方法
static all(promises){
//返回结果为promise对象
return new Promise((resolve, reject) => {
//声明变量
let count = 0;
let arr = [];
//遍历
for(let i=0;i<promises.length;i++){
//
promises[i].then(v => {
//得知对象的状态是成功
//每个promise对象 都成功
count++;
//将当前promise对象成功的结果 存入到数组中
arr[i] = v;
//判断
if(count === promises.length){
//数组里所有都成功才会修改状态
resolve(arr);
}
}, r => {
reject(r);
});
}
});
}
//添加 race 方法
static race (promises){
return new Promise((resolve, reject) => {
for(let i=0;i<promises.length;i++){
promises[i].then(v => {//谁先改变状态,谁就决定结果
//修改返回对象的状态为 『成功』
resolve(v);
},r=>{
//修改返回对象的状态为 『失败』
reject(r);
})
}
});
}
}