使用JavaScript循序渐进实现一个简单的Promise,支持异步和then链式调用。
翻译并整理自Medium: Implementing a simple Promise in Javascript - by Zhi Sun
前言
在前端面试和日常开发中,经常会接触到Promise。并且在现如今的很多面试中,也会经常被要求手写Promise。
接下来,将使用JavaScript循序渐进实现一个简单的Promise,支持异步和then链式调用。
分析Promise
Promise对象用于表示一个异步操作的最终完成 (或失败)及其结果值,常用来实现异步操作。
Promise状态
Promise有三种状态:
-
pending
初始状态
-
fulfilled
执行成功后的状态
-
rejected
执行失败后的状态
Promise状态只能由pending
改变为fulfilled
或者由pending
改变为rejected
,Promise状态改变的这一过程被称为settled
,并且,状态一旦改变,后续就不会再次被改变。
Promise构造函数中的参数
Promise构造函数接收一个函数参数executor
,该函数接收两个参数:
- resolve
- reject
执行resolve
会将Promise状态由pending
改变为fulfilled
,并触发then
方法中的成功回调函数onFulfilled
,
执行reject
会将Promise状态由pending
改变为rejected
,并触发then
方法中的失败回调函数onRejected
。
then方法中的回调函数参数
then
方法接收两个参数:
-
onFulfilled
成功回调函数,接收一个参数,即
resolve
函数中传入的值 -
onRejected
失败回调函数,接收一个参数,即
reject
函数中传入的值
如果Promise状态变为fulfilled
,就会执行成功回调函数onFulfilled
;如果Promise状态变为rejected
,就会执行失败回调函数onRejected
。
实现Promise
基础Promise
首先,constructor
接收一个函数executor
,该函数又接收两个参数,分别是resolve
和reject
函数。
因此,需要在constructor
中创建resolve
和reject
函数,并传入executor
函数中。
class MyPromise {
constructor(executor) {
const resolve = (value) => {};
const reject = (reason) => {};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
}
其次,Promise会根据状态,执行对应的回调函数。最开始的状态为pending
,当resolve
时,状态由pending
变为fulfilled
;当reject
时,状态由pending
变为rejected
。并且,一旦状态变更后,就不会再次变更。
class MyPromise {
constructor(executor) {
this.state = 'pending';
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
}
Promise状态变更后,会触发then
方法中对应的回调函数。如果状态由pending
变为fulfilled
,则会触发成功回调函数,如果状态由pending
变为rejected
,则会触发失败回调函数。
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = null;
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = reason;
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
}
if (this.state === 'rejected') {
onRejected(this.value);
}
}
}
接下来可以写点测试代码测试一下功能
const p1 = new MyPromise((resolve, reject) => resolve('resolved'));
p1.then(
(res) => console.log(res), // resolved
(err) => console.log(err)
);
const p2 = new MyPromise((resolve, reject) => reject('rejected'));
p2.then(
(res) => console.log(res),
(err) => console.log(err) // rejected
);
但是,如果用以下代码测试,会发现什么也没有输出。
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
p1.then(
(res) => console.log(res),
(err) => console.log(err)
);
const p2 = new MyPromise((resolve, reject) => {
setTimeout(() => reject('rejected'), 1000);
});
p2.then(
(res) => console.log(res),
(err) => console.log(err)
);
这是因为在调用then
方法时,Promise仍处于pending
状态。onFulfilled
和onRejected
回调函数都没有被执行。
因此,接下来需要支持异步。
支持异步的Promise
为了支持异步,需要先保存onFulfilled
和onRejected
回调函数,一旦Promise状态变化,立刻执行对应的回调函数。
⚠:这里有个细节需要注意,即onFulfilledCallbacks
和onRejectedCallbacks
是数组,因为Promise可能会被调用多次,因此会存在多个回调函数。
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = null;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach((fn) => fn(value));
}
};
const reject = (value) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = value;
this.onRejectedCallbacks.forEach((fn) => fn(value));
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
if (this.state === 'fulfilled') {
onFulfilled(this.value);
}
if (this.state === 'rejected') {
onRejected(this.value);
}
}
}
接下来可以用之前的测试代码测试一下功能
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
p1.then(
(res) => console.log(res), // resolved
(err) => console.log(err)
);
const p2 = new MyPromise((resolve, reject) => {
setTimeout(() => reject('rejected'), 1000);
});
p2.then(
(res) => console.log(res),
(err) => console.log(err) // rejected
);
但是如果用以下代码测试,会发现报错了。
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
p1.then(
(res) => console.log(res),
(err) => console.log(err)
).then(
(res) => console.log(res),
(err) => console.log(err)
); // Uncaught TypeError: Cannot read property 'then' of undefined
这是因为第一个then
方法并没有返回任何值,然而却又连续调用了then
方法。
因此,接下来需要实现then
链式调用。
支持then
链式调用的Promise
要想支持then
链式调用,then
方法需要返回一个新的Promise。
因此,需要改造一下then
方法,返回一个新的Promise,等上一个Promise的onFulfilled
或onRejected
回调函数执行完成后,再执行新的Promise的resolve
或reject
函数。
class MyPromise {
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
resolve(fulfilledFromLastPromise);
} catch (err) {
reject(err);
}
});
this.onRejectedCallbacks.push(() => {
try {
const rejectedFromLastPromise = onRejected(this.value);
reject(rejectedFromLastPromise);
} catch (err) {
reject(err);
}
});
}
if (this.state === 'fulfilled') {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
resolve(fulfilledFromLastPromise);
} catch (err) {
reject(err);
}
}
if (this.state === 'rejected') {
try {
const rejectedFromLastPromise = onRejected(this.value);
reject(rejectedFromLastPromise);
} catch (err) {
reject(err);
}
}
});
}
}
接下来可以用以下代码测试一下功能
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
p1.then(
(res) => {
console.log(res); // resolved
return res;
},
(err) => console.log(err)
).then(
(res) => console.log(res), // resolved
(err) => console.log(err)
);
const p2 = new MyPromise((resolve, reject) => {
setTimeout(() => reject('rejected'), 1000);
});
p2.then(
(res) => console.log(res),
(err) => {
console.log(err); // rejected
throw new Error('rejected');
}
).then(
(res) => console.log(res),
(err) => console.log(err) // Error: rejected
);
但是,如果改用以下代码测试,会发现第二个then
方法中的成功回调函数并没有按预期输出(‘resolved’),而是输出了上一个then
方法的onFulfilled
回调函数中返回的Promise。
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
p1.then(
(res) => {
console.log(res); // resolved
return new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
})
},
(err) => console.log(err)
).then(
(res) => console.log(res), // MyPromise {state: "pending"}
(err) => console.log(err)
);
这是因为onFulfilled
/onRejected
回调函数执行完之后,只是简单的将onFulfilled
/onRejected
执行完返回的值传入resolve
/reject
函数中执行,并没有考虑onFulfilled
/onRejected
执行完会返回一个新的Promise这种情况,所以第二次then
方法的成功回调函数中直接输出了上一次then
方法的成功回调函数中返回的Promise。因此,接下来需要解决这个问题。
首先,可以将以上测试代码改成另一种写法,方便梳理思路。
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
const p2 = p1.then(
(res) => {
console.log(res);
const p3 = new MyPromise((resolve, reject) => {
setTimeout(() => resolve('resolved'), 1000);
});
return p3;
},
(err) => console.log(err)
);
p2.then(
(res) => console.log(res),
(err) => console.log(err)
);
可以看到,一共有三个Promise:
-
第一个Promise
即通过
new
构造出来的p1 -
第二个Promise
即通过调用
then
方法返回的p2 -
第三个Promise
即在
p1.then
方法的成功回调函数参数中返回的p3
现在的问题是,调用p2的then
方法时,p3还处于pending
状态。
要想实现p2.then
方法中的回调函数能正确输出p3中resolve
/reject
之后的值,需要先等p3状态变化后再将变化后的值传入p2中的resolve
/reject
中即可。换句话说,三个Promise状态变化的先后顺序应该是p1 --> p3 --> p2。
class MyPromise {
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
if (fulfilledFromLastPromise instanceof MyPromise) {
fulfilledFromLastPromise.then(resolve, reject);
} else {
resolve(fulfilledFromLastPromise);
}
} catch (err) {
reject(err);
}
});
this.onRejectedCallbacks.push(() => {
try {
const rejectedFromLastPromise = onRejected(this.value);
if (rejectedFromLastPromise instanceof MyPromise) {
rejectedFromLastPromise.then(resolve, reject);
} else {
reject(rejectedFromLastPromise);
}
} catch (err) {
reject(err);
}
});
}
if (this.state === 'fulfilled') {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
if (fulfilledFromLastPromise instanceof MyPromise) {
fulfilledFromLastPromise.then(resolve, reject);
} else {
resolve(fulfilledFromLastPromise);
}
} catch (err) {
reject(err);
}
}
if (this.state === 'rejected') {
try {
const rejectedFromLastPromise = onRejected(this.value);
if (rejectedFromLastPromise instanceof MyPromise) {
rejectedFromLastPromise.then(resolve, reject);
} else {
reject(rejectedFromLastPromise);
}
} catch (err) {
reject(err);
}
}
});
}
}
最终版Promise
最后,一个简单的Promise就完成了,支持异步和then
链式调用。完整代码如下:
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = null;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach((fn) => fn(value));
}
};
const reject = (value) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = value;
this.onRejectedCallbacks.forEach((fn) => fn(value));
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
if (fulfilledFromLastPromise instanceof Promise) {
fulfilledFromLastPromise.then(resolve, reject);
} else {
resolve(fulfilledFromLastPromise);
}
} catch (err) {
reject(err);
}
});
this.onRejectedCallbacks.push(() => {
try {
const rejectedFromLastPromise = onRejected(this.value);
if (rejectedFromLastPromise instanceof Promise) {
rejectedFromLastPromise.then(resolve, reject);
} else {
reject(rejectedFromLastPromise);
}
} catch (err) {
reject(err);
}
});
}
if (this.state === 'fulfilled') {
try {
const fulfilledFromLastPromise = onFulfilled(this.value);
if (fulfilledFromLastPromise instanceof Promise) {
fulfilledFromLastPromise.then(resolve, reject);
} else {
resolve(fulfilledFromLastPromise);
}
} catch (err) {
reject(err);
}
}
if (this.state === 'rejected') {
try {
const rejectedFromLastPromise = onRejected(this.value);
if (rejectedFromLastPromise instanceof Promise) {
rejectedFromLastPromise.then(resolve, reject);
} else {
reject(rejectedFromLastPromise);
}
} catch (err) {
reject(err);
}
}
});
}
}
网友评论