深入JavaScript Promise:异步回调机制详解及自定义Promise实现
本文将带您深入了解JavaScript Promise的异步回调机制,并指导您亲自动手创建一个符合Promise/A+规范的Promise类。我们将重点关注Promise/A+规范中关键的规则,构建一个简化但功能完备的Promise实现。
一、核心概念
Promise: 一个带有then方法的对象或函数,其行为符合Promise/A+规范。
立即学习“Java免费学习笔记(深入)”;
Thenable: 定义了then方法的对象或函数。
Value: 任何有效的JavaScript值(包括undefined、Thenable或Promise)。
异常 (Exception): 使用throw语句抛出的值。
Reason: 表示Promise被拒绝的原因的值。
二、Promise/A+规范关键规则解读与实现
2.1 Promise状态: Promise必须处于以下三种状态之一:待处理(pending)、已完成(fulfilled)或已拒绝(rejected)。
实现:通过state属性跟踪Promise的状态,并使用value和reason属性存储相应的值和原因。状态转换仅在pending状态下进行。
class YourPromise { constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(callback => queueMicrotask(() => callback(this.value))); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(callback => queueMicrotask(() => callback(this.reason))); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } // ...then方法实现 (见下文) ... }
2.2 then方法: Promise必须提供then方法来访问其当前或最终的值或原因。then方法接受两个可选参数:onFulfilled和onRejected。
实现:then方法需要处理三种状态:pending、fulfilled和rejected。对于pending状态,回调需要入队;对于fulfilled和rejected状态,回调需要立即异步执行。 我们使用queueMicrotask确保回调在下一个微任务队列中执行,满足异步执行的要求。
then(onFulfilled, onRejected) { return new YourPromise((resolve, reject) => { if (this.state === 'fulfilled') { queueMicrotask(() => { try { const result = onFulfilled ? onFulfilled(this.value) : this.value; resolve(result); } catch (error) { reject(error); } }); } else if (this.state === 'rejected') { queueMicrotask(() => { try { const result = onRejected ? onRejected(this.reason) : this.reason; reject(result); } catch (error) { reject(error); } }); } else { this.onFulfilledCallbacks.push(() => { try { const result = onFulfilled ? onFulfilled(this.value) : this.value; resolve(result); } catch (error) { reject(error); } }); this.onRejectedCallbacks.push(() => { try { const result = onRejected ? onRejected(this.reason) : this.reason; reject(result); } catch (error) { reject(error); } }); } }); }
2.3 catch方法 (可选): 为了方便,可以添加一个catch方法,它等同于then(null, onRejected)。
catch(onRejected) { return this.then(null, onRejected); }
三、测试
您可以使用以下代码测试您的YourPromise类:
const promise = new YourPromise((resolve, reject) => { setTimeout(() => resolve('success!'), 1000); }); promise .then(value => { console.log('fulfilled with:', value); return 'next step'; }) .then(value => { console.log('chained with:', value); }); const promise2 = new YourPromise(resolve => resolve('immediately resolved!')); console.log('before then()'); promise2.then(value => console.log('inside then():', value)); console.log('after then()');
四、总结
本文提供了一个简化版的Promise实现,帮助您理解Promise/A+规范的核心概念和实现细节。 完整的Promise实现更为复杂,需要处理更多边缘情况和规范细节,例如Promise的链式调用、then方法返回Promise的处理等。 但这个简化版本足以帮助您掌握Promise的本质。 希望本文能够帮助您更好地理解和运用JavaScript Promise。
以上就是在 JavaScript 中创建您自己的 Promise的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号