JS 有什么好用的的队列组件或者代码?

2022-10-13 14:01:42 +08:00
 happy61

有一个需求,比如 设计一个队列,最高并发 2 个,我可以随时往队列放入任务,但是他只会同时执行 2 个,执行完毕后弹出队列,让下一个继续执行。 任务都是异步或者同步。

1581 次点击
所在节点    问与答
16 条回复
kop1989smurf
2022-10-13 14:06:41 +08:00
没看明白楼主的需求。
1 、并发数量可以逻辑管理,比如全局变量。
2 、都是队列了,为何还会牵扯到同步任务……
3 、“队列”你可以简单粗暴的理解为是 function 的数组。
doommm
2022-10-13 14:10:40 +08:00
看看这个? https://www.npmjs.com/package/queue
或者用 rxjs 之类的做一套
helone
2022-10-13 14:11:26 +08:00
。。。还是没太明白
ChefIsAwesome
2022-10-13 14:27:48 +08:00
rxjs 各种操作方法,做这种的多,以前写爬虫的时候用过。
happy61
2022-10-13 14:35:38 +08:00
@kop1989smurf 其实就是控制爬虫速度,避免过快。。大概可以这样理解。。要执行 100 条抓取任务,只运行 2 条同时运行
wangmn
2022-10-13 15:22:40 +08:00
wunonglin
2022-10-13 15:26:34 +08:00
rxjs
retrocode
2022-10-13 15:28:24 +08:00
async + await promise.all
veve
2022-10-13 15:32:32 +08:00
wunonglin
2022-10-13 15:37:33 +08:00
otakustay
2022-10-13 15:51:32 +08:00
p-queue 吧
happyeveryday
2022-10-13 16:05:04 +08:00
@wunonglin rx 做这方面很好用
duan602728596
2022-10-13 17:02:16 +08:00
https://github.com/duan602728596/Q/blob/main/src/Queue.ts
以前搞过限制文件上传,写过一个
netnr
2022-10-13 17:51:16 +08:00
说一下思路
数组记录队列,尾部添加,取首并删除,这是队列
任务处理,声明当前处理数量对象 C ,开始时,+1 ,任务结束时 -1 ,然后用 setInt.. 定时每 1000 毫秒包裹任务,添加判断,如果处理数对象 C<2 就执行任务处理,这是队列消费和执行任务
收尾,队列空了 暂停 在任务处理中判断
stein42
2022-10-13 18:30:34 +08:00
/*
典型的生产者消费者模型,限制并发的话只创建 2 个消费者就可以了。
Queue 用于传送任务和同步。
Queue 还可以优化,这里用 array 实现效率不高。
Queue 还可以添加容量限制。
*/

class Queue {
#queue = [];
#getter = [];

put(x) {
if (this.#getter.length > 0) {
this.#getter.shift()(x);
} else {
this.#queue.push(x);
}
}

get() {
return new Promise(resolve => {
if (this.#queue.length > 0) {
resolve(this.#queue.shift());
} else {
this.#getter.push(resolve);
}
});
}
}

function sleep(n) {
return new Promise(resolve => {
setTimeout(resolve, n);
});
}

async function consumer(queue, id) {
while (true) {
const task = await queue.get();
if (task === 'end') {
console.log(`consumer ${id}, exit`);
break;
}
console.log(`consumer ${id}, task ${task}, start`);
await sleep(1000 * Math.random());
console.log(`consumer ${id}, task ${task}, end`);
}
}

async function producer(queue) {
for (let i = 0; i < 10; i++) {
console.log(`producer, task ${i}`);
queue.put(i);
}
console.log(`producer, end`);
queue.put('end');
queue.put('end');
}

const q = new Queue();
const c = [consumer(q, 0), consumer(q, 1)];
const p = producer(q);
Pipecraft
2022-10-13 18:31:46 +08:00
这个
p-queue - https://github.com/sindresorhus/p-queue
> Promise queue with concurrency control

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/886629

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX