Appearance
并发请求池
参考文章:如何使用JavaScript实现一个带有并发限制的请求池?请提供详细的操作步骤和示例代码
js
const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
};
const delay = async (time) => {
await new Promise((resolve) => {
setTimeout(resolve, time);
});
};
module.exports = class RequestPool {
constructor(poolSize) {
this.poolSize = poolSize;
this.running = 0;
this.queue = [];
}
async addRequest(request) {
await delay(getRandomIntInclusive(0, 1000));
if (this.running > this.poolSize) {
await new Promise((resolve) => {
this.queue.push(resolve);
});
}
this.running++;
const response = await request();
this.running--;
if (this.queue.length > 0) {
this.queue.shift()();
}
return response;
}
};const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
};
const delay = async (time) => {
await new Promise((resolve) => {
setTimeout(resolve, time);
});
};
module.exports = class RequestPool {
constructor(poolSize) {
this.poolSize = poolSize;
this.running = 0;
this.queue = [];
}
async addRequest(request) {
await delay(getRandomIntInclusive(0, 1000));
if (this.running > this.poolSize) {
await new Promise((resolve) => {
this.queue.push(resolve);
});
}
this.running++;
const response = await request();
this.running--;
if (this.queue.length > 0) {
this.queue.shift()();
}
return response;
}
};js获取input元素,给value赋值无效
原因是这个页面使用了一些前端框架,比如vue。在进行数据双向绑定之后,我们使用js原生获取dom的方式去求改input元素的value值,双向绑定的机制不能检测到数据修改,因为双向绑定是通过事件进行修改数据的。
解决方法: 在修改input元素的value后,要抛出事件,来让双向绑定框架捕获到数据的修改。
js
const userNameInput = document.querySelector('input[name="username"]');
userNameInput.value = "username";
userNameInput.dispatchEvent(new Event("input"));const userNameInput = document.querySelector('input[name="username"]');
userNameInput.value = "username";
userNameInput.dispatchEvent(new Event("input"));