Promise自定义封装,Promise的各种方法的封装。
                发布人:shili8
                发布时间:2025-01-14 19:10
                阅读次数:0
                
            
             **Promise 自定义封装**
=====================在 JavaScript 中,Promise 是一个用于处理异步操作的对象。它允许你写出更简洁、更易读的代码,并且可以方便地处理复杂的异步逻辑。但是,使用 Promise 的时候,我们经常会遇到一些重复的代码和方法,这就需要我们对 Promise 进行自定义封装。
**Promise 封装**
---------------首先,让我们来看一下一个基本的 Promise 封装:
javascriptclass MyPromise {
 constructor(executor) {
 this.status = 'pending';
 this.value = null;
 this.reason = null;
 const resolve = (value) => {
 if (this.status === 'pending') {
 this.status = 'fulfilled';
 this.value = value;
 }
 };
 const reject = (reason) => {
 if (this.status === 'pending') {
 this.status = 'rejected';
 this.reason = reason;
 }
 };
 executor(resolve, reject);
 }
 then(onFulfilled, onRejected) {
 if (this.status === 'fulfilled') {
 return Promise.resolve(onFulfilled(this.value));
 } else if (this.status === 'rejected') {
 return Promise.reject(onRejected(this.reason));
 } else {
 return new MyPromise((resolve, reject) => {
 this.onFulfilled = onFulfilled;
 this.onRejected = onRejected;
 const handleValue = () => {
 try {
 const result = this.onFulfilled(this.value);
 resolve(result);
 } catch (error) {
 reject(error);
 }
 };
 const handleError = () => {
 try {
 const result = this.onRejected(this.reason);
 resolve(result);
 } catch (error) {
 reject(error);
 }
 };
 if (this.status === 'fulfilled') {
 handleValue();
 } else if (this.status === 'rejected') {
 handleError();
 } else {
 // 等待状态改变 }
 });
 }
 }
 catch(onRejected) {
 return this.then(null, onRejected);
 }
 finally(onFinally) {
 return this.then(
 (value) => Promise.resolve(onFinally()).then(() => value),
 (reason) =>
 Promise.resolve(onFinally()).catch(() => reason)
 );
 }
}
这个自定义封装提供了基本的 `then`、`catch` 和 `finally` 方法。我们可以使用它来创建新的 Promise 对象。
**Promise 的各种方法**
----------------------
### then`then` 方法用于处理成功和失败两种情况下的回调函数。它接受两个参数:`onFulfilled` 和 `onRejected`,分别对应成功和失败的回调函数。
javascriptmyPromise.then(onFulfilled, onRejected);
### catch`catch` 方法用于捕获 Promise 失败时的错误信息。它接受一个参数 `onRejected`,即失败的回调函数。
javascriptmyPromise.catch(onRejected);
### finally`finally` 方法用于在 Promise 无论成功还是失败都会执行的回调函数。它接受一个参数 `onFinally`,即最终的回调函数。
javascriptmyPromise.finally(onFinally);
**示例代码**
-------------
下面是一个使用自定义封装的 Promise 的示例:
javascriptconst myPromise = new MyPromise((resolve, reject) => {
 setTimeout(() => {
 resolve('Hello World!');
 },1000);
});
myPromise.then((value) => {
 console.log(value); // Hello World!
}).catch((error) => {
 console.error(error);
}).finally(() => {
 console.log('Finally executed');
});
这个示例代码演示了使用自定义封装的 Promise 的基本用法。
**总结**
----------
在本文中,我们对 Promise 进行了自定义封装,提供了一个基本的 `then`、`catch` 和 `finally` 方法。我们可以使用这个自定义封装来创建新的 Promise 对象,并且可以方便地处理复杂的异步逻辑。
希望这篇文章能够帮助你更好地理解和使用 Promise 的各种方法!

 粤公网安备 44011102002787号
 粤公网安备 44011102002787号