Promise
1. resolve和reject
1) 特点:
Promise的状态:pending fulfilled rejected
- 执行了resolve,Promise状态会变成fulfilled;
- 执行了reject,Promise状态会变成rejected;
- Promise状态不可逆,第一次成功就永久为fulfilled,第一次失败就永远状态为rejected;
- Promise中有throw的话,就相当于执行了reject;
2)手动实现Promise
基础能力
1> resolve 和 reject
2> state不可逆
3> throw error
class MyPromise {
// Promise的初始状态是pending;
// 需要对resolve和reject绑定this:确保resolve和reject的this指向永远指向当前的MyPromise实例,防止随着函数执行环境的改变而改变
constructor(exector) {
this.initValue(); // 初始化值
this.initBind();
try {
exector(this.reject, this.reject);
} catch (error) {
// 处理throw error
this.reject(error);
}
}
initValue() {
// 初始化
this.PromiseState = "pending"; // 状态
this.PromiseResult = null; // 终值
}
initBind() {
// 初始化this
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
}
resolve(value) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => fulfilled
this.PromiseState = "fulfilled";
this.PromiseResult = value;
}
reject(reason) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => rejected
this.PromiseState = "rejected";
this.PromiseResult = reason;
}
}
const test1 = new MyPromise((resolve, reject) => {
reject("fail");
resolve("success");
});
console.log(test1);
const test2 = new MyPromise((resolve, reject) => {
reject("fail");
});
console.log(test2);
const test3 = new MyPromise((resolve, reject) => {
throw "error";
});
console.log(test3);
then
功能:
1> 接受两个参数回调,成功回调,失败回调
2> 当Promise的状态为fulfilled时,执行成功回调;当Promise的状态为rejected时,执行失败回调
3> 当resolve或者reject在定时器中时,定时器结束后再执行回调, 此时需要缓存执行结果
4> then支持链式调用,下一次then的执行受上一次then的返回值影响
* then的第二参数(reject)和catch的区别:reject是用来抛出异常的,catch是用来处理异常的;reject是Promise的方法,then和catch是Promise实例的方法,即Promise.prototype上的方法
(1)基本使用
class MyPromise {
// Promise的初始状态是pending;
// 需要对resolve和reject绑定this:确保resolve和reject的this指向永远指向当前的MyPromise实例,防止随着函数执行环境的改变而改变
constructor(exector) {
this.initValue(); // 初始化值
this.initBind(); // 初始化this绑定
try {
exector(this.resolve, this.reject);
} catch (error) {
// 处理throw error
this.reject(error);
}
}
initValue() {
// 初始化
this.PromiseState = "pending"; // 状态
this.PromiseResult = null; // 终值
this.onFulfilledCallbacks = []; // 保存成功的回调队列
this.onRejectedCallbacks = []; // 保存失败的回调队列
}
initBind() {
// 初始化this
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
}
resolve(value) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => fulfilled
this.PromiseState = "fulfilled";
this.PromiseResult = value;
// 执行成功的回调队列
while (this.onFulfilledCallbacks.length) {
this.onFulfilledCallbacks.shift()(this.PromiseResult);
}
}
reject(reason) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => rejected
this.PromiseState = "rejected";
this.PromiseResult = reason;
// 执行失败的回调队列
while (this.onRejectedCallbacks.length) {
this.onRejectedCallbacks.shift()(this.PromiseResult);
}
}
then(onFulfilled, onRejected) {
// 参数校验:确保入参是函数形式
onFulfilled =
typeof onFulfilled === "function" ? onFulfilled : (val) => val;
onRejected = typeof onRejected === "function" ? onRejected : (err) => err;
if (this.PromiseState === "fulfilled") {
// 如果当前为成功状态,执行第一个回调
onFulfilled(this.PromiseResult);
} else if (this.PromiseState === "rejected") {
// 如果当前为失败状态,执行第二个回调
onRejected(this.PromiseResult);
} else if (this.PromiseState === "pending") {
// 当状态为pending时,缓存成功回调和失败回调
this.onFulfilledCallbacks.push(onFulfilled.bind(this));
this.onRejectedCallbacks.push(onRejected.bind(this));
}
}
}
const test1 = new MyPromise((resolve, reject) => {
resolve("success"); // 成功
// reject("fail");// 失败
// throw "error";// error
// setTimeout(() => { // 1s后执行,需要缓存then的成功回调和失败回调
// resolve("success");
// }, 1000);
});
test1.then(
(res) => console.log(res),
(err) => console.log(err)
);
(2)链式调用
class MyPromise {
// Promise的初始状态是pending;
// 需要对resolve和reject绑定this:确保resolve和reject的this指向永远指向当前的MyPromise实例,防止随着函数执行环境的改变而改变
constructor(exector) {
this.initValue(); // 初始化值
this.initBind(); // 初始化this绑定
try {
exector(this.resolve, this.reject);
} catch (error) {
// 处理throw error
this.reject(error);
}
}
initValue() {
// 初始化
this.PromiseState = "pending"; // 状态
this.PromiseResult = null; // 终值
this.onFulfilledCallbacks = []; // 保存成功的回调队列
this.onRejectedCallbacks = []; // 保存失败的回调队列
}
initBind() {
// 初始化this
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
}
resolve(value) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => fulfilled
this.PromiseState = "fulfilled";
this.PromiseResult = value;
// 执行成功的回调队列
while (this.onFulfilledCallbacks.length) {
this.onFulfilledCallbacks.shift()(this.PromiseResult);
}
}
reject(reason) {
// 只能有一个最终状态:状态不可逆
if (this.PromiseState !== "pending") return;
// 执行resolve:PromiseState => rejected
this.PromiseState = "rejected";
this.PromiseResult = reason;
// 执行失败的回调队列
while (this.onRejectedCallbacks.length) {
this.onRejectedCallbacks.shift()(this.PromiseResult);
}
}
then(onFulfilled, onRejected) {
// 参数校验:确保入参是函数形式
onFulfilled =
typeof onFulfilled === "function" ? onFulfilled : (val) => val;
onRejected = typeof onRejected === "function" ? onRejected : (err) => err;
const thenPromise = new MyPromise((newResolve, newReject) => {
const returnPromise = (cb) => {
try {
// 上一次then的执行结果的返回值,若存在 则往下执行,若无则放到新的实例中
const cbReturnResult = cb(this.PromiseResult);
if (cbReturnResult instanceof MyPromise) {
// 如果返回值是Promise
// 如果返回值是promise对象,返回值为成功,新promise就是成功
// 如果返回值是promise对象,返回值为失败,新promise就是失败
// 谁知道返回的promise是失败成功?只有then知道
cbReturnResult.then(newResolve, newReject);
} else {
// 非Promise就直接成功
newResolve(cbReturnResult);
}
} catch (error) {
newReject(error);
throw new Error(error);
}
};
if (this.PromiseState === "fulfilled") {
// 如果当前为成功状态,执行第一个回调
// onFulfilled(this.PromiseResult);
returnPromise(onFulfilled);
} else if (this.PromiseState === "rejected") {
// 如果当前为失败状态,执行第二个回调
// onRejected(this.PromiseResult);
returnPromise(onRejected);
} else if (this.PromiseState === "pending") {
// 当状态为pending时,缓存成功回调和失败回调
this.onFulfilledCallbacks.push(resolvePromise.bind(this, onFulfilled));
this.onRejectedCallbacks.push(resolvePromise.bind(this, onRejected));
}
});
// 返回这个包装的Promise
return thenPromise;
}
}
const test1 = new MyPromise((resolve, reject) => {
// resolve(100); // 成功
reject(100);
});
const p = test1.then(
(res) => new MyPromise((resolve, reject) => resolve(2 * res)),
(err) => new MyPromise((resolve, reject) => reject(3 * err))
);
// p此时为新的Promise实例
p.then(
(res) => console.log("res", res),
(err) => console.log(err)
);