若想系统学习Promise可以阅读:阮一峰大神写的Promise对象,此篇记录常用用法。
源码讲解
类写法:
step1 - 同步非链式调用
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 43 44
| const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected'
Class MyPromise { constructor(handle) { this.status = 'PENDING' this.value = undefined this.reason = undefined let resolve = (val) => { if (this.status === PENDING) { this.status = FULFILLED this.value = val } } let reject = (reason) => { if (this.status === PENDING) { this.status = REJECTED this.reason = reason } } try { handle(resolve, reject) }catch (err) { reject(err) } }
then(onFulfilled, onRejected) { if (this.status = FULFILLED) { onFulfilled(this.value) } if (this.status = REJECTED) { onRejected(this.reason) } } }
|
使用示例:
1 2 3 4 5 6 7 8 9
| function test() { return new MyPromise((resolve, reject) => { resolve(100) }) } const p1 = test() p1.then((res) => { console.log(res) })
|
构造函数写法:
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
| const PENDING = 'pending' const FULFILLED = 'fulfilled' const REJECTED = 'rejected'
function MyPromise() { this.status = 'PENDING' this.value = undefined this.reason = undefined let resolve = (val) => { if (this.status === PENDING) { this.status = FULFILLED this.value = val } } let reject = (reason) => { if (this.status === PENDING) { this.status = REJECTED this.reason = reason } } try { handle(resolve, reject) }catch (err) { reject(err) } }
|