复用请求
本文最后更新于:7 个月前
如何在web端实现异步请求结果的复用,即只产生一次 ajax 请求并保证所有调用方获取到数据。
function request() {
return new Promise((re, rj) => {
console.log("request");
setTimeout(() => {
re("我是结果");
}, 1000);
});
}
class savaResult {
constructor() {
this.p = null;
}
setRequest(request) {
let _that = this;
return request.then((res) => {
_that.p = Promise.resolve(res);
return res;
});
}
async getResult() {
return this.p;
}
}
let fn = new savaResult();
fn.setRequest(request()).then((res) => {
console.log(1, res);
console.log(3,fn.getResult())
fn.getResult().then((res) => {
console.log(2, res);
});
fn.getResult().then((res) => {
console.log(2, res);
});
fn.getResult().then((res) => {
console.log(2, res);
});
fn.getResult().then((res) => {
console.log(2, res);
});
fn.getResult().then((res) => {
console.log(2, res);
});
});
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!