/**
* 请求缓存,并调用回调
*/
function cacheRequest(fn) {
let hasReq = 1; // 未请求-1 请求中-2 请求成功-3
let result = null;
const cals = [];
return function (...args) {
const options = args[0];
const callback = args[1];
function myCallback(res) {
hasReq = 3;
result = res;
for (let i = 0; i < cals.length; i++) {
cals[i](res);
}
}
console.log('hasReq', hasReq)
if (hasReq === 1) {
hasReq = 2
cals.push(callback);
fn(options, myCallback);
} else if (hasReq === 3) {
callback(result);
} else {
cals.push(callback);
}
}
}
// 使用promise
function cacheRequest2(fn) {
let p = null;
return function (...args) {
const [options, callback] = args;
if (!p) {
p = new Promise((resolve) => {
fn(options, (res) => {
resolve(res);
})
})
}
p.then(callback);
}
}
// 使用示例
const fn = (options, callback) => {
// 发起请求等,然后调用callback
setTimeout(() => {
callback(1);
});
}
const cachedReq = cacheRequest2(fn)
cachedReq({}, (data) => {
console.log('data', data);
})
cachedReq({}, (data) => {
console.log('data', data);
})
setTimeout(() => {
cachedReq({}, (data) => {
console.log('data', data);
})
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。