码字不易,有帮助的同学希望能关注一下我的微信公众号:Code程序人生,感谢!代码自用自取。
Promise作为前端目前必不可少的内容,目前对于前端工程师的考察已经不满足于对于Promise的简单使用,中大公司的要求是知道原理,能手写实现
Promise最基本的特性,要提供三个方法,resolve、reject、then。
class Promise {
static PENDING = "PENDING";
static FULFILLED = "FULFILLED";
static REJECTED = "REJECTED";
constructor(func) {
this.status = Promise.PENDING;
this.result = null;
this.resolveCallBacks = [];
this.rejectCallBacks = [];
// 原生promise中, 如果在构造函数里throw new Error, .then的时候会走reject
// 并且会打印出throw的内容
try {
func(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(result) {
setTimeout(() => {
if (this.status === Promise.PENDING) {
this.status = Promise.FULFILLED;
this.result = result;
this.resolveCallBacks.forEach((callback) => {
callback(result);
});
}
});
}
reject(result) {
setTimeout(() => {
if (this.status === Promise.PENDING) {
this.status = Promise.REJECTED;
this.result = result;
this.rejectCallBacks.forEach((callback) => {
callback(result);
});
}
});
}
then(onFULFILLED, onREJECTED) {
return new Promise((resolve, reject) => {
onFULFILLED = typeof onFULFILLED === "function" ? onFULFILLED : () => {};
onREJECTED = typeof onREJECTED === "function" ? onREJECTED : () => {};
if (this.status === Promise.PENDING) {
this.resolveCallBacks.push(onFULFILLED);
this.rejectCallBacks.push(onREJECTED);
}
if (this.status === Promise.FULFILLED) {
setTimeout(() => {
onFULFILLED(this.result);
});
}
if (this.status === Promise.REJECTED) {
setTimeout(() => {
onREJECTED(this.result);
});
}
});
}
}
简单说几个需要注意的点:
- Promise中有三种状态,等待中PENDING,成功FULFILLED,失败REJECTED
- 构造函数中要将状态置为等待中,try catch的作用是在Promise构造函数中如何代码出现异常,会走reject的,需要用try catch来处理一下
- 两个更改方法的方法,resolve、reject,最核心的功能就是通过setTimeout来实现异步执行,执行的代码就是更改状态,保存传入的值,将其放入自己的待处理队列中
- then方法是Promise最核心的功能,在面试的时候如何对于Promise的考察浅一些,会问你为什么Promise可以实现链式调用。原理就是then方法中整体返回了一个新的Promise实例,所以才可以一直.then。对于then方法的参数的判断是因为,如果Promise的then方法,你传入的参数不是函数,它会给你转成一个空函数,这种操作需要源码处理,就是我这样的操作。然后就是判断当前的状态,等待中说明还没有执行resolve或者reject方法,就把当前的成功和失败回调放入对应的待处理队列里。如果是成功或失败,就去异步执行成功或失败的回调。
Promise的考察从初级前端到高级前端都会有,大家要深刻理解Promise的意义,才能够手写源码实现