# 动手实现一个redux-promise
上节我们分析中间件的原理和redux-thunk的实现原理,本次咱们通过redux-promise的使用来反过来推导redux-promise的实现。
redux-promise的使用
//action types
const GET_DATA = 'GET_DATA';
//action creator
const getData = function(id) {
return {
type: GET_DATA,
payload: api.getData(id) //payload为promise对象
}
}
//reducer
function reducer(oldState, action) {
switch(action.type) {
case GET_DATA:
if (action.status === 'success') {
return successState
} else {
return errorState
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
action包括一个type,payload,而在reducer中却有status,可知中间件对action进行了处理,并重新发出了新的action。
开始编写redux-promise
export default store => next => action => {
if(action.payload) {
// 需要进行处理
action.payload.then((res) => {
action = {type: action.type, status: 'success', data: res}
next(action)
}).catch(() => {
action = {type: action.type, status: 'fail', data: {}}
next(action)
})
} else {
next(action)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
我在中间件中对action进行判断payload(简单判断,没有对类型判断,勉强忽略了),在payload执行完成后,发出一个新的action,大概实现原理就是这样了,有兴趣的可以试试实现redux-promise-middleware,关于thunk,promise,promise-middleware三者的区别,可以看Redux异步方案选型