1 |
|
2 |
|
3 |
|
4 |
|
5 | import uniqueId from 'mini-unique-id'
|
6 |
|
7 | function isPromise(val) {
|
8 | return val && typeof val.then === 'function'
|
9 | }
|
10 |
|
11 | export default function promiseMiddleware({ dispatch }) {
|
12 | return next => action => {
|
13 | if (isPromise(action.payload)) {
|
14 | const sequenceId = uniqueId()
|
15 |
|
16 | dispatch({
|
17 | ...action,
|
18 | payload: undefined,
|
19 | sequence: {
|
20 | type: 'start',
|
21 | id: sequenceId
|
22 | }
|
23 | })
|
24 |
|
25 | return action.payload.then(
|
26 | result => dispatch({
|
27 | ...action,
|
28 | payload: result,
|
29 | sequence: {
|
30 | type: 'next',
|
31 | id: sequenceId
|
32 | }
|
33 | }),
|
34 | error => dispatch({
|
35 | ...action,
|
36 | payload: error,
|
37 | error: true,
|
38 | sequence: {
|
39 | type: 'next',
|
40 | id: sequenceId
|
41 | }
|
42 | })
|
43 | )
|
44 | }
|
45 |
|
46 | return next(action)
|
47 | }
|
48 | }
|