手写Promise,实现then和catch方法
手写 Promise 类,包含 then
方法和 catch
方法:
class MyPromise { constructor(executor) { this.state = 'pending'; this.value = undefined; this.error = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach((callback) => callback(this.value)); } }; const reject = (error) => { if (this.state === 'pending') { this.state = 'rejected'; this.error = error; this.onRejectedCallbacks.forEach((callback) => callback(this.error)); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value; onRejected = typeof onRejected === 'function' ? onRejected : (error) => { throw error; }; return new MyPromise((resolve, reject) => { const handleFulfilled = () => { setTimeout(() => { try { const result = onFulfilled(this.value); resolve(result); } catch (error) { reject(error); } }); }; const handleRejected = () => { setTimeout(() => { try { const result = onRejected(this.error); resolve(result); } catch (error) { reject(error); } }); }; if (this.state === 'fulfilled') { handleFulfilled(); } else if (this.state === 'rejected') { handleRejected(); } else if (this.state === 'pending') { this.onFulfilledCallbacks.push(handleFulfilled); this.onRejectedCallbacks.push(handleRejected); } }); } catch(onRejected) { return this.then(undefined, onRejected); } }
这个手写的 Promise 类包含 then
方法和 catch
方法,并且能够正常处理 Promise 的链式调用和异常捕获。
测试示例:
const promise = new MyPromise((resolve, reject) => { // 异步操作 setTimeout(() => { resolve('Promise resolved'); // reject(new Error('Promise rejected')); }, 1000); }); promise .then((data) => { console.log(data); // 输出:Promise resolved return 'New data'; }) .then((data) => { console.log(data); // 输出:New data throw new Error('Custom error'); }) .catch((error) => { console.error(error); // 输出:Custom error });
在上面的例子中,我们创建了一个简单的 Promise,并通过 then
方法链式调用,然后使用 catch
方法捕获异常。