Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。
实现一个基本的Promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| 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: } } }
|