import axios from 'axios' // 數據存儲 export const cache = { data: {}, set (key, data) { this.data[key] = data }, get (key) { return this.data[key] }, clear (key) { delete this.data[key] } } // 創建惟一的key值 export const buildUniqueUrl = (url, method, params = {}, data = {}) => { const paramStr = (obj) => { if (toString.call(obj) === '[object Object]') { return JSON.stringify(Object.keys(obj).sort().reduce((result, key) => { result[key] = obj[key] return result }, {})) } else { return JSON.stringify(obj) } } url += `?${paramStr(params)}&${paramStr(data)}&${method}` return url } // 防止重複請求 export default (options = {}) => async config => { const defaultOptions = { time: 0, // 設置爲0,不清除緩存 ...options } const index = buildUniqueUrl(config.url,config.method,config.params,config.data) let responsePromise = cache.get(index) if (!responsePromise) { responsePromise = (async () => { try { const response = await axios.defaults.adapter(config) return Promise.resolve(response) } catch (reason) { cache.clear(index) return Promise.reject(reason) } })() cache.set(index, responsePromise) if (defaultOptions.time !== 0) { setTimeout(() => { cache.clear(index) }, defaultOptions.time) } } return responsePromise.then(data => JSON.parse(JSON.stringify(data))) // 爲防止數據源污染 }
例如javascript
import axios from 'axios' import cache from './cache' // get請求 export async function getData (payload) { return axios.get('/path', { params: payload, adapter: cache({ time: 0 }) }) } // post請求 export async function postData (payload) { return axios.post('/path', payload, { adapter: cache({ time: 1000 }) }) }
time 表示可緩存的時間,默認爲0,在沒有清除內存以前永久緩存(瀏覽器窗口標籤關閉,應用程序關閉等會清除內存)java
time 設置一個極短的時間,好比1000,就表示在1000毫秒以內不會重複向服務器發出請求,固然你也能夠用new CancelToken,但會致使本次請求報錯,須要作異常處理ios