今天是星期六,写个笔记记下我的学习历程,自己有点小菜,把博客拿来当笔记写哈哈哈哈哈哈哈哈哈~~
Promise是用来许下承诺的(可不会遭雷劈哦!),我承诺我会努力往上爬的,信不信咱们在未来瞧瞧好了^_-
接收Promise状态改变有着年长的then方法,还有着async await修饰符(听说还有些浏览器不支持)。async await真的挺好的,阅读代码更加的舒服了。我来记录一下学习Promise时模拟封装的MyPromise构造函数… 简易的封装下啦~
先写下思路:
- 三个常量存储着三个状态:pending、resolved和rejected。
- 实例属性有着value(改变状态时接收的值)、status(当前状态)、resolvedCallBackList(存放状态变为resolve时触发的回调函数)、rejectedCallBackList(存放状态变为rejected时触发的回调函数)。
- 在构造函数中定义两个状态改变时触发的函数。
- 在MyPromise构造函数原型对象上定义一个then方法,接收成功与失败时的回调函数。当状态是pending时同步操作直接调用then方法里的两个回调函数;当状态时resolved/rejected时异步操作,将这两个回调函数放入到对应的数组中(第二步定义的),等掉状态改变再来拿出来执行。
异步操作放入到数组中,运用的是闭包原理,我的异步操作没结束我的作用域就还在,嘻嘻嘻。贴代码咯 ~
const PENDING = "pending";
const RESOLVED = "resolved";
const REJECTED = "rejected";
function MyPromise(fn){
const _this = this; // 存一下this指向的MyPromise
_this.value = null; // 初始value值为空
_this.status = PENDING; // 初始状态为pending
_this.resolvedCallBackList = []; // 存放then里面成功的回调函数
_this.rejectedCallBackList = []; // 存放then里面失败的回调函数
// 定义两个成功/失败函数
function resolve(value){
console.log(value instanceof MyPromise);
// 状态是pending才让你改变状态、value值执行成功的回调函数
if(_this.status === PENDING){
_this.value = value;
_this.status = RESOLVED;
_this.resolvedCallBackList.forEach(cb => cb(_this.value));
}
}
function reject(value){
// 也是一样的,状态只能是从pending -> resolved/rejected
if(_this.status === PENDING){
_this.value = value;
_this.status = REJECTED;
_this.rejectedCallBackList.forEach(cb => cb(_this.value));
}
}
// 将传的函数调用,将resolve和reject两个函数作为实参传过去
try{
fn(resolve, reject);
}catch(err){
reject(err);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected){
const _this = this;
// 判断是否传的是函数,不是函数就要创建一个函数并赋给对应的参数
onFulfilled = typeof onFulfilled === "function" ? onFulfilled : item => item;
onRejected = typeof onRejected === "function" ? onRejected : item => item;
// 当是异步操作时,把成功与失败的函数都放在对应的数组里
// 当是同步操作时,状态已经改变了,不用放入数组中,直接调用传的函数
if(_this.status === PENDING){
_this.resolvedCallBackList.push(onFulfilled);
_this.rejectedCallBackList.push(onRejected);
} else if(_this.status === RESOLVED) onFulfilled(_this.value);
else if(_this.status === REJECTED) onRejected(_this.value);
}
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(11111);
});
});
promise.then(value => {console.log(value);}, value => {console.log(value);});
最后说下不足之处:Promise的then方法返回值又是一个Promise实例,可以达到链式效果。我这个简易的封装不能有这个效果,思想有待提升。待我知识进步进化之日,再来加油改进!!!