返回
掌握 Promise,解锁 JavaScript 异步编程的奥秘
前端
2023-10-13 22:59:23
ES6 到 ES10:Promise 基本使用和手动封装
前言
在当今快节奏的 Web 开发世界中,处理异步任务已成为开发人员必备的技能。Promise 是 JavaScript 中一种强大的工具,可以帮助我们优雅地处理这些异步任务,让我们的代码更加健壮和可维护。
Promise 基本介绍
Promise 是一个对象,它代表了异步操作的最终完成或失败的结果。我们可以使用它来处理各种异步任务,如网络请求、文件读取或超时事件。
Promise 有三种状态:
- Pending: 初始状态,表示操作尚未完成。
- Fulfilled: 操作已成功完成,并带有结果值。
- Rejected: 操作已失败,并带有错误值。
使用 Promise
要使用 Promise,我们可以使用 then()
方法来处理操作完成后的结果,或者使用 catch()
方法来处理操作失败时的错误。
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
手动封装 Promise
虽然 JavaScript 提供了内置的 Promise,但我们也可以手动封装自己的 Promise。这在需要自定义 Promise 行为或创建自定义异步操作时很有用。
class MyPromise {
constructor(executor) {
this.state = 'pending';
this.result = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
executor(
(result) => {
this.fulfill(result);
},
(error) => {
this.reject(error);
}
);
}
fulfill(result) {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.result = result;
this.onFulfilledCallbacks.forEach(callback => callback(result));
}
}
reject(error) {
if (this.state === 'pending') {
this.state = 'rejected';
this.result = 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.result);
} else if (this.state === 'rejected') {
onRejected(this.result);
}
return this;
}
catch(onRejected) {
this.then(null, onRejected);
return this;
}
}
结论
Promise 是 JavaScript 中处理异步编程的宝贵工具。通过了解其基本概念和手动封装能力,我们可以自信地编写健壮、可维护和高效的异步代码。掌握 Promise,解锁 JavaScript 异步编程的奥秘,让你的 Web 应用程序更上一层楼。