手寫 Promise:深入理解異步編程的基石
本文將帶您逐步實現一個簡單的 Promise,以幫助您深入理解異步編程的基本概念。通過自己動手編寫 Promise 的過程,您將更好地理解 Promise 的工作原理和常見用法,并能夠應用于實際項目中。
Promise 的基本結構
Promise 是一個構造函數,它接受一個執行器函數作為參數。在執行器函數中,我們可以進行異步操作,并根據操作的結果來調用 Promise 的 resolve 和 reject 方法。
class MyPromise {constructor(executor) {this.state = 'pending';this.value = undefined;this.callbacks = [];const resolve = (value) => {if (this.state === 'pending') {this.state = 'fulfilled';this.value = value;this.callbacks.forEach(callback => this.executeCallback(callback));}};const reject = (reason) => {if (this.state === 'pending') {this.state = 'rejected';this.value = reason;this.callbacks.forEach(callback => this.executeCallback(callback));}};executor(resolve, reject);}executeCallback(callback) {const { onFulfilled, onRejected, resolve, reject } = callback;try {if (this.state === 'fulfilled') {const value = onFulfilled ? onFulfilled(this.value) : this.value;resolve(value);} else if (this.state === 'rejected') {const value = onRejected ? onRejected(this.value) : this.value;reject(value);}} catch (error) {reject(error);}}
}
添加 then 方法
Promise 的 then 方法用于指定完成和失敗時的回調函數。在我們手動實現的 Promise 中,我們將回調函數包裝成一個對象,保存在 Promise 的 callbacks 數組中。
class MyPromise {// ...then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {const callback = {onFulfilled,onRejected,resolve,reject,};if (this.state === 'pending') {this.callbacks.push(callback);} else {this.executeCallback(callback);}});}
}
錯誤處理和鏈式調用
為了實現錯誤處理和鏈式調用,我們需要在 then 方法中返回一個新的 Promise 對象,以便將每個 then 方法的返回值傳遞給下一個 then 方法。
class MyPromise {// ...then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {const callback = {onFulfilled,onRejected,resolve,reject,};if (this.state === 'pending') {this.callbacks.push(callback);} else {setTimeout(() => {this.executeCallback(callback);});}});}catch(onRejected) {return this.then(null, onRejected);}
}
完成最終的 Promise 實現
最終,我們的手寫 Promise 實現如下:
class MyPromise {constructor(executor) {// ...executor(resolve, reject);}// ...then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {const callback = {onFulfilled,onRejected,resolve,reject,};if (this.state === 'pending') {this.callbacks.push(callback);} else {setTimeout(() => {this.executeCallback(callback);});}});}catch(onRejected) {return this.then(null, onRejected);}
}
通過自己實現一個簡單的 Promise,我們更深入地理解了 Promise 的工作原理和常見用法。了解 Promise 的基本結構和方法之后,您將能夠更好地應用 Promise 來處理異步操作,提高代碼的可讀性和維護性。
請注意,這只是一個簡化版的 Promise 實現,真實的 Promise 還有更多復雜的特性和處理方式。為了生產環境中的實際項目,請使用現有的成熟 Promise 實現,如 JavaScript 中的原生 Promise