【每日一題】請實現(xiàn)一個 cacheRequest 方法

人生苦短,總需要一點儀式感。比如學前端~
請實現(xiàn)一個 cacheRequest 方法,保證發(fā)出多次同一個 ajax 請求時都能拿到的數(shù)據(jù),而實際上只發(fā)出一次請求。
我的思路:
/* 準備一個緩存map,key為請求條件,值為第一次請求的響應結(jié)果。后續(xù)請求條件相同,直接返回map內(nèi)的對應結(jié)果,不再發(fā)起請求。
cacheRequestMap = {
'get-api/request_api/01': {
request: {},
response: data
}
} */
import axios from 'axios';
let cacheRequestMap = {}
function cacheRequest({
url,
type,
params
}) {
let key = type + url
return new Promise((res, rej) => {
if(cacheRequestMap[key]) {
res(cacheRequestMap[key].response)
} else {
axios[type]({
url,
params
})
.then((data) => {
cacheRequestMap[key].response = data
res(data)
})
.catch((err) => {
rej(err)
})
}
})
}
// 調(diào)用方式
cacheRequest({
url: '/request_api/01',
type: 'get',
params: ''
})
.then((data) => {
})
.catch((err) => {
})
參考答案
const request = (url, option) =>
new Promise((res) => {
setTimeout(() => {
res({ data: option });
}, 2000);
});
const cache = new Map();
const cacheRequest = (url, option) => {
let key = `${url}:${option.method}`;
if (cache.has(key)) {
if (cache.get(key).status === "pending") {
return cache.get(key).myWait;
}
return Promise.resolve(cache.get(key).data);
} else {
// 無緩存,發(fā)起真實請求
let requestApi = request(url, option);
cache.set(key, { status: "pending", myWait: requestApi });
return requestApi
.then((res) => {
// console.log(cache)
cache.set(key, { status: "success", data: res });
// console.log(cache)
return Promise.resolve(res);
})
.catch((err) => {
cache.set(key, { status: "fail", data: err });
Promise.reject(err);
});
}
};
實現(xiàn)原理
cache 構(gòu)建 Map,用作緩存數(shù)據(jù),把 URL 作為 key,用來判斷是否來自同一個請求
請求的更多參數(shù)可傳入 option,例如 get,data…
每次請求檢查緩存,有的話就返回緩存,沒有的話發(fā)起請求
請求成功后,保存數(shù)據(jù)到 cache 并返回,失敗則彈框提示
特殊情況,如果請求在 pending 狀態(tài),則返回該請求繼續(xù)等待
代碼中 ajax 請求用 setTimeout()函數(shù)代替,可自行封裝 request 函數(shù)

讓我們一起攜手同走前端路!

評論
圖片
表情
