494 字
1 分钟
手写 Promise:从基础到符合 A+ 规范
手写一个符合 Promise/A+ 规范的 Promise,理解异步编程的核心机制。
先回顾一下 Promise 的基本用法
const p = new Promise((resolve, reject) => { setTimeout(() => { resolve('成功') // reject('失败') }, 1000)})
p.then( value => console.log('成功:', value), reason => console.log('失败:', reason))一个 Promise 有三种状态:
- pending(等待中):初始状态
- fulfilled(已完成):操作成功
- rejected(已拒绝):操作失败
状态只能从 pending → fulfilled 或 pending → rejected,不可逆。
第一步:实现基础结构
class MyPromise { constructor(executor) { // 初始状态 this.status = 'pending' this.value = undefined this.reason = undefined
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 立即执行 try { executor(resolve, reject) } catch (err) { reject(err) } }
then(onFulfilled, onRejected) { if (this.status === 'fulfilled') { onFulfilled(this.value) } if (this.status === 'rejected') { onRejected(this.reason) } }}测试:
const p = new MyPromise((resolve, reject) => { resolve('hello')})
p.then( value => console.log(value), // hello reason => console.log(reason))基础结构有了,但有个大问题:异步的时候不生效。
const p = new MyPromise((resolve, reject) => { setTimeout(() => resolve('hello'), 1000)})
p.then(value => console.log(value)) // 什么都不输出!因为 then 执行的时候,状态还是 pending,回调没被保存。
第二步:处理异步——发布订阅模式
class MyPromise { constructor(executor) { this.status = 'pending' this.value = undefined this.reason = undefined // 新增:回调队列 this.onFulfilledCallbacks = [] this.onRejectedCallbacks = []
const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled' this.value = value // 执行所有成功回调 this.onFulfilledCallbacks.forEach(fn => fn()) } }
const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected' this.reason = reason // 执行所有失败回调 this.onRejectedCallbacks.forEach(fn => fn()) } }
try { executor(resolve, reject) } catch (err) { reject(err) } }
then(onFulfilled, onRejected) { if (this.status === 'fulfilled') { onFulfilled(this.value) } if (this.status === 'rejected') { onRejected(this.reason) } // pending 状态:保存回调 if (this.status === 'pending') { this.onFulfilledCallbacks.push(() => onFulfilled(this.value)) this.onRejectedCallbacks.push(() => onRejected(this.reason)) } }}测试:
const p = new MyPromise((resolve, reject) => { setTimeout(() => resolve('hello'), 1000)})
p.then(value => console.log(value)) // 1秒后输出: hello异步处理好了。但 then 返回的不是 Promise,不能链式调用。
第三步:实现链式调用
这是 Promise 最核心的特性。then 必须返回一个新的 Promise。
class MyPromise { // ... 构造函数不变
then(onFulfilled, onRejected) { // 返回新的 Promise const promise2 = new MyPromise((resolve, reject) => { if (this.status === 'fulfilled') { // 用微任务模拟异步 queueMicrotask(() => { try { const x = onFulfilled(this.value) resolvePromise(promise2, x, resolve, reject) } catch (err) { reject(err) } }) }
if (this.status === 'rejected') { queueMicrotask(() => { try { const x = onRejected(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (err) { reject(err) } }) }
if (this.status === 'pending') { this.onFulfilledCallbacks.push(() => { queueMicrotask(() => { try { const x = onFulfilled(this.value) resolvePromise(promise2, x, resolve, reject) } catch (err) { reject(err) } }) }) this.onRejectedCallbacks.push(() => { queueMicrotask(() => { try { const x = onRejected(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (err) { reject(err) } }) }) } })
return promise2 }}关键函数 resolvePromise: 处理 then 回调返回值的各种情况
function resolvePromise(promise2, x, resolve, reject) { // 防止循环引用 if (promise2 === x) { return reject(new TypeError('循环引用')) }
// 如果 x 是 Promise,就采用它的状态 if (x instanceof MyPromise) { x.then(resolve, reject) return }
// 如果 x 是普通值,直接 resolve resolve(x)}测试链式调用:
new MyPromise((resolve) => { resolve(1)}) .then(value => { console.log(value) // 1 return value + 1 }) .then(value => { console.log(value) // 2 return value * 2 }) .then(value => { console.log(value) // 4 })链式调用成功!
第四步:值穿透
原生 Promise 有一个特性:如果 then 的参数不是函数,会直接穿透。
Promise.resolve(1) .then(2) // 不是函数,穿透 .then(Promise.resolve(3)) // 不是函数,穿透 .then(value => console.log(value)) // 输出 1实现值穿透:
then(onFulfilled, onRejected) { // 参数处理:不是函数就忽略,用默认函数 onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value onRejected = typeof onFulfilled === 'function' ? onRejected : reason => { throw reason }
// ... 后续逻辑不变}第五步:实现 catch 和 finally
class MyPromise { // catch 就是 then 的语法糖 catch(onRejected) { return this.then(null, onRejected) }
// finally 不管成功失败都执行 finally(callback) { return this.then( value => MyPromise.resolve(callback()).then(() => value), reason => MyPromise.resolve(callback()).then(() => { throw reason }) ) }
// 静态方法:resolve static resolve(value) { if (value instanceof MyPromise) return value return new MyPromise(resolve => resolve(value)) }
// 静态方法:reject static reject(reason) { return new MyPromise((_, reject) => reject(reason)) }}测试:
new MyPromise((resolve) => { resolve('成功')}) .finally(() => { console.log('不管成功失败都执行') }) .then(value => { console.log(value) // 成功 })第六步:实现 all 和 race
class MyPromise { static all(promises) { return new MyPromise((resolve, reject) => { const results = [] let count = 0
promises.forEach((promise, index) => { MyPromise.resolve(promise).then( value => { results[index] = value count++ if (count === promises.length) { resolve(results) } }, reason => reject(reason) ) }) }) }
static race(promises) { return new MyPromise((resolve, reject) => { promises.forEach(promise => { MyPromise.resolve(promise).then(resolve, reject) }) }) }
// 补充:allSettled static allSettled(promises) { return new MyPromise((resolve) => { const results = [] let count = 0
promises.forEach((promise, index) => { MyPromise.resolve(promise).then( value => { results[index] = { status: 'fulfilled', value } }, reason => { results[index] = { status: 'rejected', reason } } ).finally(() => { count++ if (count === promises.length) { resolve(results) } }) }) }) }}测试:
const p1 = new MyPromise(r => setTimeout(() => r(1), 1000))const p2 = new MyPromise(r => setTimeout(() => r(2), 500))const p3 = new MyPromise(r => setTimeout(() => r(3), 200))
MyPromise.all([p1, p2, p3]).then(values => { console.log(values) // [1, 2, 3]})
MyPromise.race([p1, p2, p3]).then(value => { console.log(value) // 3(最先完成的)})第七步:用 Promise/A+ 测试工具验证
# 安装测试工具npm install -g promises-aplus-tests// 在文件末尾加上适配器MyPromise.deferred = function () { const result = {} result.promise = new MyPromise((resolve, reject) => { result.resolve = resolve result.reject = reject }) return result}
module.exports = MyPromisepromises-aplus-tests your-file.js跑完 872 个测试用例全过,就说明你的 Promise 实现是符合规范的。
完整代码
把上面的所有步骤合并,就是一个完整的 Promise 实现:
class MyPromise { constructor(executor) { this.status = 'pending' this.value = undefined this.reason = undefined this.onFulfilledCallbacks = [] this.onRejectedCallbacks = []
const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled' this.value = value this.onFulfilledCallbacks.forEach(fn => fn()) } }
const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected' this.reason = reason this.onRejectedCallbacks.forEach(fn => fn()) } }
try { executor(resolve, reject) } catch (err) { reject(err) } }
then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
const promise2 = new MyPromise((resolve, reject) => { const handle = (fn, value) => { queueMicrotask(() => { try { const x = fn(value) resolvePromise(promise2, x, resolve, reject) } catch (err) { reject(err) } }) }
if (this.status === 'fulfilled') handle(onFulfilled, this.value) if (this.status === 'rejected') handle(onRejected, this.reason) if (this.status === 'pending') { this.onFulfilledCallbacks.push(() => handle(onFulfilled, this.value)) this.onRejectedCallbacks.push(() => handle(onRejected, this.reason)) } })
return promise2 }
catch(fn) { return this.then(null, fn) }
finally(fn) { return this.then( value => MyPromise.resolve(fn()).then(() => value), reason => MyPromise.resolve(fn()).then(() => { throw reason }) ) }
static resolve(v) { return v instanceof MyPromise ? v : new MyPromise(r => r(v)) } static reject(r) { return new MyPromise((_, rej) => rej(r)) }
static all(promises) { return new MyPromise((resolve, reject) => { const results = []; let count = 0 promises.forEach((p, i) => { MyPromise.resolve(p).then(v => { results[i] = v; count++ if (count === promises.length) resolve(results) }, reject) }) }) }
static race(promises) { return new MyPromise((resolve, reject) => { promises.forEach(p => MyPromise.resolve(p).then(resolve, reject)) }) }}
function resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) return reject(new TypeError('循环引用')) if (x instanceof MyPromise) { x.then(resolve, reject); return } resolve(x)}总结
手写 Promise 涉及的核心知识点:
- 状态机:pending / fulfilled / rejected,状态不可逆
- 发布订阅:异步场景下保存回调,状态变更后执行
- 链式调用:then 返回新 Promise,resolvePromise 处理返回值
- 微任务:用 queueMicrotask 模拟异步执行时机
- 值穿透:then 参数非函数时自动透传
写一遍下来,对 Promise 的工作机制会清楚很多。
分享
如果这篇文章对你有帮助,欢迎分享给更多人!
手写 Promise:从基础到符合 A+ 规范
https://www.403bug.top/posts/handwrite-promise/ 部分信息可能已经过时
相关文章 智能推荐





