Source code series:

  • SPA Router v5.x SPA Router v5.x SPA Router
  • Redux v4. X source code analysis

In the previous article, the actions were all synchronized, that is, the dispatches (actions) were updated by the middleware to get synchronized state.

Here are some actions that are executed asynchronously.

redux-thunk

Redux-chunk is a middleware component of Redux that creates an asynchronous action.

How does that work? First of all, what is thunk?

thunk

Thunk is a function that contains an expression for delayed execution.

let x = 1 + 2;
let foo = (a)= > 1 + 2;
Copy the code

Foo () returns 3 only if it is executed, so foo is the chunk function.

Redux-thunk redux-thunk redux-thunk redux-thunk

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) = > next => action= > {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
export default thunk;

Copy the code

As shown in the source code, redux-thunk is a middleware that differs from other middleware in that it executes the action when it determines that the action type is a function. The synchronized action execution returns an object.

Example:

// Execute next(action) at dispatch(action) when passing through the middleware and update to get state synchronized.
const loading = text= > ({
  type: 'LOADING',
  text
})

const cancelLoading = text= > ({
  type: 'CANCEL_LOADING',
  text
})

// Dispatch (action) executes the action(... Args), the update results in state being asynchronous.
const fetchPeople = (url, params) = > {
  return ({dispatch, getState}) = > {
    dispatch(loading('start loading'));
    fetch(url, params).then(delayPromise(3000)).then(data= > {
      dispatch(cancelLoading('cancel loading'));
    });
  };
};
Copy the code

Online example

redux-promise

Redux-promise is also middleware and works in much the same way as Redux-thunk, except that redux-Promise uses promise asynchronicity.

The source code is as follows:

import isPromise from 'is-promise';
import { isFSA } from 'flux-standard-action';

export default function promiseMiddleware({ dispatch }) {
  return next= > action => {
    if(! isFSA(action)) {return isPromise(action) ? action.then(dispatch) : next(action);
    }

    return isPromise(action.payload)
      ? action.payload
          .then(result= >dispatch({ ... action,payload: result }))
          .catch(error= >{ dispatch({ ... action,payload: error, error: true });
            return Promise.reject(error);
          })
      : next(action);
  };
}
Copy the code

Redux-promise is compatible with the FSA standard (payload is the result information). The implementation process is to determine whether the action or action. Payload is a promise object. Otherwise the next (action).

communication

Here is the blog address, feel good to click a Star, thank you ~

Github.com/hankzhuo/Bl…