手写Promise
相关经常是各大公司手撕代码环节会被问到的问题,本文手把手带你实现一遍Promise
的核心功能和方法。
const test = new Promise((reslove, reject) => {
reslove("siu");
});
test.then((res) => {
console.log(res); // siu
});
接下来实现这一部分功能
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class selfPromise {
constructor(exec) {
this.status = PENDING;
this.result = null;
// 用bind绑定this或resolve和reject用箭头函数 让它绑定到实例
exec(this.resolve.bind(this), this.reject.bind(this));
}
resolve(result) {
// 只有在PENDING状态下,才需要改变状态和记录结果
// 这样也保证了Promise状态一旦改变就不能再改变
// reject和reslove相同
if (this.status === PENDING) {
this.status = FULFILLED;
this.result = result;
}
}
reject(reason) {
if (this.status === PENDING) {
this.status = REJECTED;
this.result = reason;
}
}
then(onFULFILLED, onREJECTED) {
if (this.status === FULFILLED) {
onFULFILLED(this.result);
}
if (this.status === REJECTED) {
onREJECTED(this.result);
}
}
}
const test = new selfPromise((resolve, reject) => {
resolve("siu is good");
// reject("reject is good");
});
test.then(
(res) => {
console.log(res); // siu is good
},
(rej) => {
console.log(rej); //reject is good
}
);
const test = new selfPromise((resolve, reject) => {
setTimeout(() => {
resolve("siu is good");
});
// throw new Error("error");
});
test.then(
(res) => {
console.log(res); // 无输出
},
(rej) => {
console.log(rej);
}
);
因为setTimeout
方法执行将resolve
函数导致then
方法比resolve
先执行,所以当时Promise状态为pending
,在then
中还没有处理pending
的情况,导致无输出。
处理执行函数时如果抛出错误 这时Promise
的状态因由pending
转为rejected
,而捕获异常需要用到try catch
constructor(exec) {
this.status = PROMISE_PENDING_STATE;
this.result = null;
this.reason = null;
this.resolveCallbacks = [];
this.rejectCallbacks = [];
try {
exec(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(result) {
if (this.status === PENDING) {
this.status = FULFILLED;
this.result = result;
this.resolveCallbacks.forEach((fn) => {
fn(result);
});
}
}
reject(reason) {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.rejectCallbacks.forEach((fn) => {
fn(reason);
});
}
}
then(onFULFILLED, onREJECTED) {
if (this.status === PENDING) {
this.resolveCallbacks.push(onFULFILLED);
this.rejectCallbacks.push(onREJECTED);
}
if (this.status === FULFILLED) {
onFULFILLED(this.result);
}
if (this.status === REJECTED) {
onREJECTED(this.reason);
}
}
}
const test = new selfPromise((resolve, reject) => {
setTimeout(() => {
resolve("siu is good");
});
// throw new Error("error");
});
test.then(
(res) => {
console.log(res); // siu is good
},
(rej) => {
console.log(rej); //reject is good
}
);
then
函数参数 then(onFULFILLED, onREJECTED) {
// Promise 中的 then 方法回调参数都是可选的,当调用 then 方法未传参数时,需要给默认值
onFULFILLED =
typeof onFULFILLED === "function"
? onFULFILLED
// 值穿透
: (value) => {
return value;
};
onREJECTED =
typeof onREJECTED === "function"
? onREJECTED
: (reason) => {
throw reason;
};
...
}
Promise
中then
方法是异步执行的。让then
方法在同步任务完成后执行,通过setTimeout
方法将then
方法的执行延后,在同步任务执行完毕后then
方法才会被调用。 resolve(result) {
setTimeout(() => {
if (this.status === PENDING) {
this.status = FULFILLED;
this.result = result;
this.resolveCallbacks.forEach((fn) => {
fn(result);
});
}
});
}
reject(reason) {
setTimeout(() => {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.rejectCallbacks.forEach((fn) => {
fn(reason);
});
}
});
}
then(onFULFILLED, onREJECTED) {
if (this.status === PENDING) {
this.resolveCallbacks.push(onFULFILLED);
this.rejectCallbacks.push(onREJECTED);
}
if (this.status === FULFILLED) {
setTimeout(() => {
onFULFILLED(this.result);
});
}
if (this.status === REJECTED) {
setTimeout(() => {
onREJECTED(this.reason);
});
}
}
}
console.log("1");
const test = new selfPromise((resolve, reject) => {
resolve("siu is good");
});
test.then(
(res) => {
console.log("3 " + res);
},
(rej) => {}k
);
console.log("2");
//输出
//1
//2
//3 siu is good
then
方法的链式调用 要实现链式调用需要让then
方法有返回值并且是Promise
对象 下一个then
方法会依赖上一个then
方法的回调函数返回值 then(onFULFILLED, onREJECTED) {
...
//重复逻辑太多抽离成函数
const fn = (fn) => {
try {
const result = fn(this.result);
if (result instanceof selfPromise) {
result.then(
(res) => {
resolve(res);
// console.log(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} catch (err) {
reject(err);
}
};
if (this.status === FULFILLED) {
setTimeout(() => {
// try {
// const result = onFULFILLED(this.result);
// resolvePromise(newPromise, result, resolve, reject);
// } catch (error) {
// reject(error);
// }
fn(onFULFILLED);
});
}
if (this.status === REJECTED) {
setTimeout(() => {
// try {
// const reason = onREJECTED(this.result);
// resolvePromise(newPromise, reason, resolve, reject);
// } catch (error) {
// reject(error);
// }
fn(onREJECTED);
});
}
if (this.status === PENDING) {
this.resolveCallbacks.push(() => {
// try {
// const result = onFULFILLED(this.result);
// resolvePromise(newPromise, result, resolve, reject);
// } catch (error) {
// reject(error);
// }
fn(onFULFILLED);
});
this.rejectCallbacks.push(() => {
// try {
// const result = onREJECTED(this.result);
// resolvePromise(newPromise, result, resolve, reject);
// } catch (error) {
// reject(error);
// }
fn(onREJECTED);
});
}
});
return newPromise;
}
const test = new selfPromise((resolve, reject) => {
resolve("siu is good");
});
test
.then((res) => {
console.log("1 " + res);
return new selfPromise((resolve, reject) => {
resolve(res);
});
})
.then((res) => {
console.log(res);
});
// 1 siu is good
// siu is good
catch(onRejected)
:该方法是 then()
方法的一个特殊形式,用于注册对 Promise
拒绝状态的处理函数。它只接收一个参数 onRejected
,表示在 Promise
拒绝时要执行的回调函数。catch()
方法也返回一个新的 Promise
对象,可以用于链式调用。
catch(onREJECTED) {
return this.then(null, onREJECTED);
}
const test = new selfPromise((resolve, reject) => {
reject("siu siu siu");
});
test.then().catch((rea) => {
console.log(rea);
});
// siu siu siu
finally(onFinally)
:该方法在 Promise
的状态最终确定后执行指定的回调函数,无论是解决还是拒绝状态。它接收一个参数 onFinally
,表示要执行的回调函数。finally()
方法返回一个新的 Promise
对象,可以用于链式调用。
finally(onFinally) {
return this.then(
(value) => selfPromise.resolve(onFinally()).then(() => value),
(reason) =>
selfPromise.resolve(onFinally()).then(() => {
throw reason;
})
);
}
const test = new selfPromise((resolve, reject) => {
reject("siu siu siu");
//resolve("666");
});
test
.then()
.catch((rea) => {
console.log(rea);
})
.finally(() => {
console.log("123");
});
//siu siu siu
//123
??? all
:该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise
对象。这个新的 Promise
对象在所有传入的 Promise
都解决时才会解决,并把所有解决结果按顺序作为数组传递给回调函数。如果传入的 Promise
中有任何一个被拒绝,它将立即拒绝并把第一个拒绝原因传递给回调函数
static all(promises) {
let result = [];
let resolveCount = 0;
return new selfPromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
// 记录数据
result[i] = res;
resolveCount++;
if (resolveCount === promises.length) {
resolve(result);
}
},
(reason) => {
reject(reason);
}
);
}
});
}
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t = selfPromise.all([t1, t2, t3]).then((res) => {
console.log(res);
});
any:Promise.any(iterable)
该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise
对象。这个新的 Promise
对象在传入的任意一个 Promise
解决时立即解决,并将该解决值传递给回调函数。如果传入的所有 Promise
都被拒绝,它将立即拒绝并把所有拒绝原因作为数组传递给回调函数。
static any(promises) {
return new selfPromise((resolve, reject) => {
const errors = [];
let completedCount = 0;
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
resolve(res);
},
(err) => {
errors.push({ index: i, err});
completedCount++;
if (completedCount === promises.length) {
reject(new AggregateError(errors));
}
}
);
}
});
}
race(iterable)
:该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise
对象。这个新的 Promise
对象在传入的任意一个 Promise
解决或拒绝时立即解决或拒绝,并把第一个解决或拒绝的结果传递给回调函数。
static race(promises) {
return new selfPromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
resolve(res);
},
(reason) => {
reject(reason);
}
);
}
});
}
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t4 = Promise.reject("4");
selfPromise.race([t2, t1, t3, t4]).then((res) => {
console.log(res);
});
// 2
allSettled:
该方法接收一个可迭代对象(比如数组)作为参数,返回一个新的 Promise
对象。这个新的 Promise
对象在传入的所有 Promise
都已解决或拒绝时才会解决,并把所有 Promise
的最终结果作为对象数组传递给回调函数。每个对象包含一个 status
属性,表示 Promise
的状态(“fulfilled” 表示解决,“rejected” 表示拒绝),以及一个 value
或 reason
属性,分别表示解决值或拒绝原因。
static allSettled(promises) {
return new selfPromise((resolve) => {
const results = [];
let pendingCount = promises.length;
for (let i = 0; i < promises.length; i++) {
promises[i]
.then(
(value) => {
results[i] = { status: "fulfilled", value };
},
(reason) => {
results[i] = { status: "rejected", reason };
}
)
.finally(() => {
pendingCount--;
if (pendingCount === 0) {
resolve(results);
}
});
}
});
}
const t1 = Promise.resolve("1");
const t2 = Promise.resolve("2");
const t3 = Promise.resolve("3");
const t4 = Promise.reject("4");
selfPromise.allSettled([t1, t2, t3, t4]).then((res) => {
console.log(res);
});
// [
// { status: 'fulfilled', value: '1' },
// { status: 'fulfilled', value: '2' },
// { status: 'fulfilled', value: '3' },
// { status: 'rejected', reason: '4' }
// ]
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class selfPromise {
constructor(exec) {
this.status = PENDING;
this.result = null;
this.resolveCallbacks = [];
this.rejectCallbacks = [];
exec(this.resolve.bind(this), this.reject.bind(this));
}
resolve(result) {
setTimeout(() => {
if (this.status === PENDING) {
this.status = FULFILLED;
this.result = result;
this.resolveCallbacks.forEach((fn) => {
fn(result);
});
}
});
}
reject(result) {
setTimeout(() => {
if (this.status === PENDING) {
this.status = REJECTED;
this.result = result;
this.rejectCallbacks.forEach((fn) => {
fn(result);
});
}
});
}
then(onFULFILLED, onREJECTED) {
// Promise 中的 then 方法回调参数都是可选的,当调用 then 方法未传参数时,需要给默认值
onFULFILLED =
typeof onFULFILLED === "function"
? onFULFILLED
: (value) => {
return value;
};
onREJECTED =
typeof onREJECTED === "function"
? onREJECTED
: (reason) => {
throw reason;
};
const newPromise = new selfPromise((resolve, reject) => {
const fn = (fn) => {
try {
const result = fn(this.result);
if (result instanceof selfPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
} catch (err) {
reject(err);
}
};
if (this.status === FULFILLED) {
setTimeout(() => {
fn(onFULFILLED);
});
}
if (this.status === REJECTED) {
setTimeout(() => {
fn(onREJECTED);
});
}
if (this.status === PENDING) {
this.resolveCallbacks.push(() => {
fn(onFULFILLED);
});
this.rejectCallbacks.push(() => {
fn(onREJECTED);
});
}
});
return newPromise;
}
catch(onREJECTED) {
return this.then(null, onREJECTED);
}
finally(onFinally) {
return this.then(
(value) => selfPromise.resolve(onFinally()).then(() => value),
(reason) =>
selfPromise.resolve(onFinally()).then(() => {
throw reason;
})
);
}
static resolve(result) {
return new selfPromise((resolve, reject) => {
if (result instanceof selfPromise) {
result.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
} else {
resolve(result);
}
});
}
static reject(result) {
return new selfPromise((resolve, reject) => {
reject(result);
});
}
static all(promises) {
let result = [];
let resolveCount = 0;
return new selfPromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
// 记录数据
result[i] = res;
resolveCount++;
if (resolveCount === promises.length) {
resolve(result);
}
},
(reason) => {
reject(reason);
}
);
}
});
}
static any(promises) {
return new selfPromise((resolve, reject) => {
const errors = [];
let completedCount = 0;
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
resolve(res);
},
(err) => {
errors.push({ index: i, err });
completedCount++;
if (completedCount === promises.length) {
reject(new AggregateError(errors));
}
}
);
}
});
}
static race(promises) {
return new selfPromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
resolve(res);
},
(reason) => {
reject(reason);
}
);
}
});
}
static allSettled(promises) {
return new selfPromise((resolve) => {
const results = [];
let pendingCount = promises.length;
for (let i = 0; i < promises.length; i++) {
promises[i]
.then(
(value) => {
results[i] = { status: FULFILLED, value };
},
(reason) => {
results[i] = { status: REJECTED, reason };
}
)
.finally(() => {
pendingCount--;
if (pendingCount === 0) {
resolve(results);
}
});
}
});
}
}
代码可优化的东西很多,更多作为自我学习,也希望对你有所帮助。