uniapp 中使用getAPP 创建了全局变量,值是一个类实例,更改属性之后getAPP获取不到最新的值?
我写了一个限制请求数量的类文件,在getAPP中创建这个实例,然后加入方法,然后再获取请求的数量,数量一直是0,没有更新。
/**
*@description
*@author cy
*@date 2022-10-20 09:52
**/
export class LimitRequest {
private limit: number = 1; // 限制并发数量
private currentSum: number = 0; // 当前发送数量
private requests: Array<any> = []; // 请求
constructor(limit: number) {
this.limit = limit;
this.currentSum = 0;
this.requests = [];
}
public request(reqFn: Function) {
if (!reqFn || !(reqFn instanceof Function)) {
console.error('当前请求不是一个Function', reqFn);
return;
}
this.requests.push(reqFn);
if (this.currentSum < this.limit) {
this.run();
}
}
public stop() {
this.requests = [];
this.currentSum = 0;
}
public getParam() {
return { currentSum: this.currentSum, requests: this.requests.length };
}
async run() {
try {
++this.currentSum;
const fn = this.requests.shift();
await fn();
console.error('this.requests', this.requests.length);
} catch (err) {
console.log('Error', err);
} finally {
--this.currentSum;
if (this.requests.length > 0) {
this.run();
}
}
}
}
加入request方法模拟请求,
globalData: {
limitAjax: new LimitRequest(10)
},
for (let i = 0; i < 20; i++) {
getApp().globalData.limitAjax.request(() => {
setTimeout(() => {
let params = getApp().globalData.limitAjax.getParam();
console.error('parma', params);
}, 1000)
})
}
打印中的request.length 一直是0,这是为什么呢?求助
因为调用
request
时传入的方法没有返回Promise