
Product
Announcing Socket Fix 2.0
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
task-queue-lib
Advanced tools
任务队列
nodejs 任务队列, 针对请求、IO 操作或其他异步操作高并发削峰的解决方案
npm install task-queue-lib
或
yarn add task-queue-lib
或
pnpm install task-queue-lib
import { TaskQueue } from "task-queue-lib";
const { TaskQueue } = require("task-queue-lib");
<script src="./node_modules/task-queue-lib/dist/umd/index.js"></script>
<script>
console.log(TaskQueue);
</script>
const taskQueue = new TaskQueue({ maxLen: 10 });
const taskQueue = new TaskQueue({ maxLen: 10 });`
`taskQueue.push([() => {}])
taskQueue.push(syncFn.bind(null, "args"));
taskQueue.push([() => {}]).then(console.log); // [ undefined ]
或
taskQueue.on(taskQueue.defaultKey, console.log).push([() => {}]);
const fn = (params) => params;
taskQueue.push([fn.bind(this, "hello")], "task1");
taskQueue.push([fn.bind(this, "world")], "task1").then(console.log); // [ 'hello', 'world' ]
taskQueue.push([fn.bind(this, "world")], "task2").then(console.log); // [ 'world' ]
taskQueue.unshift(3);
taskQueue.clearQueue();
当我们通过 maxLen 将 push 的队列进行拆分,可以监听队列的步进事件,比如队列长度为 10,maxLen 为 3,那么就会执行 4 次步进函数及事件。
// 实例化TaskQueue对象时,传入函数stepCb可以收到队列每次执行的消息。此外通过使用on方法,可以监听队列的步进事件,事件命名规则是`${key}:${step}`,key是taskQueue.push的第二个参数,step是当前队列的步进值。
const stopFn = async () => {
const stopQueue = new TaskQueue({
maxLen: 1,
stepCb: (data) => {
// data类型参考:IStepCbParams
console.log(data);
},
});
const key = "key1";
const queue = [
() => Promise.resolve("hello"),
() => Promise.resolve("1"),
() => Promise.resolve("stop"),
() => Promise.resolve("2"),
() => Promise.reject("3"),
];
stopQueue.push(queue, "key1");
for (let i = 1; i < queue.length + 1; i++) {
stopQueue.on(key + `:${i}`, (data) => {
const isStop = data.step === 3;
console.log(isStop);
if (isStop) stopQueue.clearQueue(); // 停止队列后续操作
});
}
};
stopFn();
FAQs
nodejs消息队列
We found that task-queue-lib demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.
Product
Socket’s new Tier 1 Reachability filters out up to 80% of irrelevant CVEs, so security teams can focus on the vulnerabilities that matter.