2

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

 1 year ago
source link: https://www.v2ex.com/t/886629
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

V2EX  ›  问与答

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

  happy61 · 4 小时 45 分钟前 · 535 次点击

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

16 条回复    2022-10-13 18:31:46 +08:00

kop1989smurf      4 小时 40 分钟前

没看明白楼主的需求。1 、并发数量可以逻辑管理,比如全局变量。2 、都是队列了,为何还会牵扯到同步任务……3 、“队列”你可以简单粗暴的理解为是 function 的数组。

helone      4 小时 35 分钟前

。。。还是没太明白

ChefIsAwesome      4 小时 18 分钟前

rxjs 各种操作方法,做这种的多,以前写爬虫的时候用过。

happy61      4 小时 11 分钟前

@kop1989smurf 其实就是控制爬虫速度,避免过快。。大概可以这样理解。。要执行 100 条抓取任务,只运行 2 条同时运行

wunonglin      3 小时 20 分钟前

retrocode      3 小时 18 分钟前

async + await promise.all

otakustay      2 小时 55 分钟前

p-queue 吧

netnr      55 分钟前 via Android

说一下思路数组记录队列,尾部添加,取首并删除,这是队列任务处理,声明当前处理数量对象 C ,开始时,+1 ,任务结束时 -1 ,然后用 setInt.. 定时每 1000 毫秒包裹任务,添加判断,如果处理数对象 C<2 就执行任务处理,这是队列消费和执行任务收尾,队列空了 暂停 在任务处理中判断

stein42      16 分钟前

/*
典型的生产者消费者模型,限制并发的话只创建 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);


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK