background

Description: There are some AXIos requests, when the return failure, if the specific error code is returned in this case 400, error code field 00001, need to invoke the authentication component, after successful authentication, need to obtain its token, re-launch the request

thinking

Since redux-saga is used, this axios request is also made in Effect. The original intention is to reset Effect after the component validates successfully. But effect has an input parameter. In this case, you need to keep the previous effect input parameter, and the whole thing becomes troublesome. Later, considering the AXIos return, you can get the parameters of the HTTP request, and AXIos has a method to directly accept these parameters and initiate the same request, eliminating the process of data assembly. The second AXIos request triggers the consideration of the Promise because the promise doesn’t execute its callback until the state changes; At the same time, promises can pass the required tokens

Pseudo code

axios.js

import store from '/store'; / / redux store instance. Interceptors. Response. Use ((response) = > {... }, // Handle (error) => {const {response} = error; const { status , data:code, config} = response; if(code === 00001){ const { headers, ... rest } = config; Headers store.dispatch(showComp()); // Execute effect, control component displays let captchaResolve; new Promise((resolve, reject) => { store.dispatch(setPromise(resolve)); }). Then ((token) => {captchaResolve(token); // Change the next promise state}); new Promise((resolve) => { captchaResolve = resolve; }). Then ((token) => {// Get token, request instance.request({... rest, headers: { ... headers, [Headers.VERIFICATION_TOKEN]: token }, }); }); }Copy the code

effects.js

function verify(params){ ... Const {token} = response; axiosPromise && axiosPromise(token); // axiosPromise is the promise passed in by setPromise.Copy the code