若想系统学习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 // 失败状态的失败原因

// 成功时改变状态,并赋值value
let resolve = (val) => {
if (this.status === PENDING) {
this.status = FULFILLED
this.value = val
}
}
// 失败时改变状态,并赋值reason
let reject = (reason) => {
if (this.status === PENDING) {
this.status = REJECTED
this.reason = reason
}
}
// catch住当前同步代码的错误
try {
handle(resolve, reject)
}catch (err) {
reject(err)
}
}

// then时根据状态执行回调
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 // 失败状态的失败原因

// 成功时改变状态,并赋值value
let resolve = (val) => {
if (this.status === PENDING) {
this.status = FULFILLED
this.value = val
}
}
// 失败时改变状态,并赋值reason
let reject = (reason) => {
if (this.status === PENDING) {
this.status = REJECTED
this.reason = reason
}
}

// catch住当前同步代码的错误
try {
handle(resolve, reject)
}catch (err) {
reject(err)
}
}
// TODO then方法
阅读全文 »