面试中碰见手写Promise就抓瞎研究了一下根据Promise A规范手写了个Promise//新增三种状态 const STATUS_PENDING pending; const STATUS_FULFILLED fulfilled; const STATUS_REJECTED rejected; class _Promise { constructor(executor () {}) { //立即执行构造函数且状态变为pending this.status STATUS_PENDING; this.value undefined; this.reason undefined; const resolve (value) { //只有当状态是pending时执行resolve后状态变为fullfilled if(this.status STATUS_PENDING){ this.status STATUS_FULFILLED this.value value } }; const reject (reason) { //只有当状态是pending时执行reject后状态变为rejected if(this.status STATUS_PENDING){ this.status STATUS_REJECTED this.reason reason } }; executor(resolve, reject); } then(onFulfilled, onRejected){ if(onFulfilled typeof onFulfilled function){ onFulfilled(this.value) } if(onRejected typeof onRejected function){ onRejected(this.reason) } } catch(onRejected) { if(onRejected typeof onRejected function){ onRejected(this.reason) } } }
手写Promise1
发布时间:2026/6/6 10:36:43
面试中碰见手写Promise就抓瞎研究了一下根据Promise A规范手写了个Promise//新增三种状态 const STATUS_PENDING pending; const STATUS_FULFILLED fulfilled; const STATUS_REJECTED rejected; class _Promise { constructor(executor () {}) { //立即执行构造函数且状态变为pending this.status STATUS_PENDING; this.value undefined; this.reason undefined; const resolve (value) { //只有当状态是pending时执行resolve后状态变为fullfilled if(this.status STATUS_PENDING){ this.status STATUS_FULFILLED this.value value } }; const reject (reason) { //只有当状态是pending时执行reject后状态变为rejected if(this.status STATUS_PENDING){ this.status STATUS_REJECTED this.reason reason } }; executor(resolve, reject); } then(onFulfilled, onRejected){ if(onFulfilled typeof onFulfilled function){ onFulfilled(this.value) } if(onRejected typeof onRejected function){ onRejected(this.reason) } } catch(onRejected) { if(onRejected typeof onRejected function){ onRejected(this.reason) } } }