Promise

Martin

一个保存着未来才会结束的事件结果的容器

Promiseb包含三种状态pending(进行中)、fullfilled(已完成)、rejected(已失败)

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
43
44
45
46
47
48
49
50
51
52
53
// Promise.all
// 全部成功时才触发,返回一个包含promise数组的结果
// 场景: 并发无相互依赖接口时
Promise.all([
// api1
// api2
// api3
])

// Promise.allSettle
// 全部结束时才触发,返回一个包含所有成功或失败的promise数组的结果
// 场景:批处理且能容忍失败的场景如日志上传
Promise.allSettle([
// 上传日志1
// 上传日志2
// 上传日志3
])

// Promise.any
// 第一个promise成功执行后触发,都失败才返回失败
// 场景: cdn资源竞争,抢票
Promise.any([ 'cdn1', 'cdn2', 'cdn3' ]).then()
Promise.any([ '抢票地址1', '抢票地址2' ]).then()

// Promise.race
// 返回第一个无论成功或失败的结果
// 场景:1、请求超时处理,
// 2、从两个api地址请求,返回响应最快的结果
// 场景:超时
function selfFetch(api, { timeout }) {
return Promise.race([
// 模拟发送请求
new Promise(resolve => {
setTimeout(() => {
resolve(`fetch ${api} success`, );
}, 500);
}),
// 模拟超时
// 接口 1000ms后 直接reject 返回超时提示
new Promise((resolve, reject) => {
setTimeout(() => {
reject(`fetch ${api} timeout`)
}, timeout)
})
])
}

selfFetch('/api/user', { timeout: 1000 }).then(res => {
console.log('success', res);
}).catch(error => {
console.log('error', error);
})

手写promise: ES5版

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function MyPromise (executor) {
// 定义状态和结果
this.state = 'pending'
this.value = undefined

// 定义接受回调结果的数组
this.callbacks = []

// 定义resolve和reject方法
const resolve = (value) => {
// 只在pending状态才进入
if(this.state === 'pending') {
// 改变状态和结果
this.state = 'fulfilled'
this.value = value
this.callbacks.forEach((handle)=>{
handle.onFulfilled(value)
})
}
}
const reject = (value) => {
// 只在pending状态才进入
if(this.state === 'pending') {
// 改变状态和结果
this.state = 'rejected'
this.value = value
this.callbacks.forEach((handle)=>{
handle.onRejected(value)
})
}
}

// 执行executor
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}

// 定义then方法
MyPromise.prototype.then = function (onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value)
} else if(this.state === 'rejected') {
onRejected(this.value)
} else {
this.callbacks.push({
onFulfilled,
onRejected
})
console.log(this.callbacks)
}
}
}

// 测试用例

const p1 = new MyPromise((resolve, reject)=>{
setTimeout(()=>{
resolve('成功')
},2000)
})
p1.then((res)=>{console.log(res)},()=>{})

手写promise: ES6版

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class MyPromise {
// 定义执行器
constructor (executor) {
// 定义状态和结果
this.state = 'pending'
this.value = undefined

// 定义接受回调结果的数组
this.callbacks = []
const resolve = (value)=> {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
this.callbacks.forEach((handle)=>{
handle.onFulfilled(value)
})
}
}
const reject = (value) => {
// 只在pending状态才进入
if(this.state === 'pending') {
// 改变状态和结果
this.state = 'rejected'
this.value = value
this.callbacks.forEach((handle)=>{
handle.onRejected(value)
})
}
}
try{
executor(resolve,reject)
} catch (e) {
reject(e)
}

}
then (onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value)
} else if(this.state === 'rejected') {
onRejected(this.value)
} else {
this.callbacks.push({
onFulfilled,
onRejected
})
console.log(this.callbacks)
}
}
}

// 测试用例

const p1 = new MyPromise((resolve, reject)=>{
setTimeout(()=>{
resolve('成功')
},2000)
})
p1.then((res)=>{console.log(res)},()=>{})