返回
**用 TDD 方式编写一个更好的 Promise
前端
2023-11-17 05:02:39
正文:
TDD(测试驱动开发)是一种软件开发方法,强调在编写代码之前先编写测试用例。这可以帮助我们确保代码从一开始就满足要求,并随着时间的推移保持健壮性。
让我们从了解原生 Promise 语法开始:
const promise = new Promise((resolve, reject) => {
// 异步操作
if (成功) {
resolve(结果);
} else {
reject(错误);
}
});
Promise 有三个状态:pending
(等待中)、fulfilled
(已完成,表示操作成功)和 rejected
(已拒绝,表示操作失败)。
要测试 Promise,我们可以使用 Jest 等测试框架。以下是原生 Promise 的一个示例测试:
test('promise resolves with value', () => {
const promise = new Promise((resolve) => {
resolve('foo');
});
return promise.then((value) => {
expect(value).toBe('foo');
});
});
现在,让我们根据这些知识来编写自己的 MyPromise 实现:
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.error = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
try {
executor(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve(value) {
if (this.state !== 'pending') return;
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => callback(value));
}
reject(error) {
if (this.state !== 'pending') return;
this.state = 'rejected';
this.error = error;
this.onRejectedCallbacks.forEach((callback) => callback(error));
}
then(onFulfilled, onRejected) {
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
} else if (this.state === 'fulfilled') {
onFulfilled(this.value);
} else if (this.state === 'rejected') {
onRejected(this.error);
}
}
}
我们的 MyPromise 实现了与原生 Promise 相同的 API,但提供了更多的灵活性。我们可以使用它来创建更高级别的异步操作,例如并行处理和超时。
TDD 是一种强大的技术,可以帮助我们编写更可靠、更健壮的代码。通过编写测试用例,我们可以确保我们的代码从一开始就满足要求,并随着时间的推移保持健壮性。