如何解决Chrome Tab重复项未发出网络请求
我在应用程序加载(componentDidMount)上有3个api调用。
当我重新加载页面或打开新标签页时,会进行所有api调用,但是在复制标签页时,只会触发其中的一个。
如何触发页面复制中的所有api调用
注意: 浏览器:chrome。
解决方法
使用Memopromise工具是处理异步过程的有效工具。
class MemoPromise {
constructor(getPromise) {
this.cache = {};
this.getPromise = getPromise;
this.request = this.request.bind(this);
}
request({ uniqueKey,...rest }) {
if (!uniqueKey) {
return Promise.reject(new Error('Unique key not passed'));
}
if (this.cache[uniqueKey]) {
return this.cache[uniqueKey];
}
const promise = this.getPromise(rest);
this.cache[uniqueKey] = promise
.then((res) => {
delete this.cache[uniqueKey];
return res;
})
.catch((err) => {
delete this.cache[uniqueKey];
throw err;
});
return this.cache[uniqueKey];
}
}
在上面的示例中,我创建了一个MemoPromise类,该类的实例化对象可以记住构造函数中传递的函数返回的承诺,直到它们未被解析或拒绝为止。
查看执行代码
const memoPromise = new MemoPromise(fn);
// invocation
const { request } = memoPromise;
request({ uniqueKey: url,apiType,url,payload });
// not required now
// fn({ apiType,payload });
在将Memopromise类集成到您的浏览器之后,您的API请求可能不会遇到任何问题。它可以有效地处理您的重复请求。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。