**题目:** 请实现一个合乎规范的 Promise 方法。 **参考答案:** ```js class Promise { constructor (fn) { // 三个状态 this.state = 'pending' this.value = undefined this.reason = undefined let resolve = value => { if (this.state === 'pending') { this.state = 'fulfilled' this.value = value } } let reject = value => { if (this.state === 'pending') { this.state = 'rejected' this.reason = value } } // 自动执行函数 try { fn(resolve, reject) } catch (e) { reject(e) } } // then then(onFulfilled, onRejected) { switch (this.state) { case 'fulfilled': onFulfilled() break case 'rejected': onRejected() break default: } } } /** * 作者:陈煜仑 * 链接:https://juejin.im/post/5d2ee123e51d4577614761f8 * 来源:掘金 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ ```
Activity
[-]第 36 期(W3C 标准-ECMAScript-语法):实现一个Promise方法[/-][+]第 36 期(W3C 标准-JavaScript-异步):实现一个Promise方法[/+]