Node.JS多线程PromisePool之promise-pool库实现
什么是Promise Pool

Map-like, concurrent promise processing for Node.js.
Promise-Pool是一个用于管理并发请求的JavaScript库,它可以限制同时进行的请求数量,以避免过多的请求导致服务器压力过大。使用Promise-Pool可以方便地实现对多个异步操作的并发控制。
Promise Pool “承诺池” 包允许您批量运行许多承诺。
承诺池确保并发处理任务的最大数量。
承诺池中的每个任务都是其他任务,这意味着一旦一个任务完成,池就开始处理下一个任务。
此处理可确保了为您的任务进行最佳的批处理。
Promise Pool - NPMJS
@supercharge/promise-pool - npm (npmjs.com)
https://www.npmjs.com/package/@supercharge/promise-pool
Promise Pool - Document
Promise Pool
https://superchargejs.com/docs/3.x/promise-pool
怎么使用PromisePool
Install 安装
so easy , just install it
npm i @supercharge/promise-pool
Usage用例
Using the promise pool is pretty straightforward. The package exposes a class and you can create a promise pool instance using the fluent interface.
使用promise pool承诺池非常简单。该包公开了一个类,您可以使用流畅的接口创建一个承诺池实例。
Here’s an example using a concurrency of 2:
import { PromisePool } from '@supercharge/promise-pool'const users = [{ name: 'Marcus' },{ name: 'Norman' },{ name: 'Christian' }
]const { results, errors } = await PromisePool.withConcurrency(2).for(users).process(async (userData, index, pool) => {const user = await User.createIfNotExisting(userData)return user})
The promise pool uses a default concurrency of 10
默认是十个线程,请按照自己的实际情况(业务+架构)处理
在以下示例中,我们创建了一个包含5个worker的线程池。然后,我们向线程池添加了10个任务。线程池会并发执行这些任务,但最多只能有5个任务同时运行。当一个任务完成时,线程池会自动分配下一个任务给空闲的worker。
const PromisePool = require('promise-pool');// 创建一个包含5个worker的线程池
const pool = new PromisePool(5, (task) => {return new Promise((resolve, reject) => {// 模拟一个耗时操作setTimeout(() => {console.log('Task completed:', task);resolve();}, 1000);});
});// 添加任务到线程池
for (let i = 0; i < 10; i++) {pool.addTask(i).then(() => {console.log('Task finished:', i);}).catch((err) => {console.error('Error:', err);});
}//zhengkai.blog.csdn.net
Manually Stop the Pool 手工停止
You can stop the processing of a promise pool using the pool instance provided to the .process() and .handleError() methods. Here’s an example how you can stop an active promise pool from within the .process() method:
await PromisePool.for(users).process(async (user, index, pool) => {if (condition) {return pool.stop()}// processes the `user` data})
You may also stop the pool from within the .handleError() method in case you need to:
import { PromisePool } from '@supercharge/promise-pool'await PromisePool.for(users).handleError(async (error, user, pool) => {if (error instanceof SomethingBadHappenedError) {return pool.stop()}// handle the given `error`}).process(async (user, index, pool) => {// processes the `user` data})
Bring Your Own Error Handling
The promise pool allows for custom error handling. You can take over the error handling by implementing an error handler using the .handleError(handler).
If you provide an error handler, the promise pool doesn’t collect any errors. You must then collect errors yourself.
Providing a custom error handler allows you to exit the promise pool early by throwing inside the error handler function. Throwing errors is in line with Node.js error handling using async/await.
承诺池允许自定义错误处理。
您可以通过使用.手柄错误(处理程序)实现错误处理程序来接管错误处理。
如果您提供了一个错误处理程序,则承诺池不会收集任何错误。
然后,您必须自己收集错误。
提供了一个自定义的错误处理程序,允许您通过抛出错误处理程序函数来提前退出承诺池。
抛出错误与Node.js错误处理使用异步/等待相一致。
import { PromisePool } from '@supercharge/promise-pool'try {const errors = []const { results } = await PromisePool.for(users).withConcurrency(4).handleError(async (error, user) => {if (error instanceof ValidationError) {errors.push(error) // you must collect errors yourselfreturn}if (error instanceof ThrottleError) { // Execute error handling on specific errorsawait retryUser(user)return}throw error // Uncaught errors will immediately stop PromisePool}).process(async data => {// the harder you work for something,// the greater you’ll feel when you achieve it})await handleCollected(errors) // this may throwreturn { results }
} catch (error) {await handleThrown(error)
}
Callback for Started and Finished Tasks 开始和结束任务的回调
You can use the onTaskStarted and onTaskFinished methods to hook into the processing of tasks. The provided callback for each method will be called when a task started/finished processing:
您可以使用任务启动和任务完成的方法来连接到任务的处理中。
当任务启动/完成处理时,将调用为每个方法提供的回调:
import { PromisePool } from '@supercharge/promise-pool'await PromisePool.for(users).onTaskStarted((item, pool) => {console.log(`Progress: ${pool.processedPercentage()}%`)console.log(`Active tasks: ${pool.processedItems().length}`)console.log(`Active tasks: ${pool.activeTasksCount()}`)console.log(`Finished tasks: ${pool.processedItems().length}`)console.log(`Finished tasks: ${pool.processedCount()}`)}).onTaskFinished((item, pool) => {// update a progress bar or something else :)}).process(async (user, index, pool) => {// processes the `user` data})
You can also chain multiple onTaskStarted and onTaskFinished handling (in case you want to separate some functionality):import { PromisePool } from '@supercharge/promise-pool'await PromisePool.for(users).onTaskStarted(() => {}).onTaskStarted(() => {}).onTaskFinished(() => {}).onTaskFinished(() => {}).process(async (user, index, pool) => {// processes the `user` data})
Task Timeouts 超时设置
有时,配置一个任务必须完成处理的超时时间是很有用的。
一个超时的任务被标记为失败。
您可以使用与任务超时(<毫秒>)方法来配置任务的超时:
Sometimes it’s useful to configure a timeout in which a task must finish processing. A task that times out is marked as failed. You may use the withTaskTimeout(<milliseconds>) method to configure a task’s timeout:
import { PromisePool } from '@supercharge/promise-pool'await PromisePool.for(users).withTaskTimeout(2000) // milliseconds.process(async (user, index, pool) => {// processes the `user` data})
Notice: a configured timeout is configured for each task, not for the whole pool. The example configures a 2-second timeout for each task in the pool.
注意:为每个任务配置了一个已配置的超时,而不是为整个池。
该示例为池中的每个任务配置一个2秒的超时。
Correspond Source Items and Their Results 正确响应每个请求
有时,您希望处理后的结果与源项保持一致。
结果项在结果数组中的位置应该与其相关的源项相同。
使用使用对应结果方法来应用此行为:
Sometimes you want the processed results to align with your source items. The resulting items should have the same position in the results array as their related source items. Use the useCorrespondingResults method to apply this behavior:
import { setTimeout } from 'node:timers/promises'
import { PromisePool } from '@supercharge/promise-pool'const { results } = await PromisePool.for([1, 2, 3]).withConcurrency(5).useCorrespondingResults().process(async (number, index) => {const value = number * 2return await setTimeout(10 - index, value)})/*** source array: [1, 2, 3]* result array: [2, 4 ,6]* --> result values match the position of their source items*/
For example, you may have three items you want to process. Using corresponding results ensures that the processed result for the first item from the source array is located at the first position in the result array (=index 0). The result for the second item from the source array is placed at the second position in the result array, and so on …
例如,您可能有三个要处理的项目。
使用相应的结果可以确保从源数组中得到的第一个项的处理结果位于结果数组中的第一个位置(=索引0)。
来自源数组的第二个项的结果被放置在结果数组中的第二个位置,以此类推。
Return Values When Using Corresponding Results 在使用相应的结果时,请返回相应的值
The results array returned by the promise pool after processing has a mixed return type. Each returned item is one of this type:
- the actual value type: for results that successfully finished processing
Symbol('notRun'): for tasks that didn’t runSymbol('failed'): for tasks that failed processing
The PromisePool exposes both symbols and you may access them using
Symbol('notRun'): exposed asPromisePool.notRunSymbol('failed'): exposed asPromisePool.failed
处理后由承诺池返回的结果数组具有混合返回类型。
每个返回的项目都是以下类型之一:
实际值类型:对于成功完成处理的结果
符号(“notRun”):用于未运行的任务
符号(“failed”):用于处理失败的任务
承诺池公开了这两个符号,您可以使用
符号(“notRun”):公开为PromisePool.notRun
符号(“failed”):公开为PromisePool.failed
您可以对所有未运行或失败的任务重复处理:
You may repeat processing for all tasks that didn’t run or failed:
import { PromisePool } from '@supercharge/promise-pool'const { results, errors } = await PromisePool.for([1, 2, 3]).withConcurrency(5).useCorrespondingResults().process(async (number) => {// …})const itemsNotRun = results.filter(result => {return result === PromisePool.notRun
})const failedItems = results.filter(result => {return result === PromisePool.failed
})
When using corresponding results, you need to go through the errors array yourself. The default error handling (collect errors) stays the same and you can follow the described error handling section above.
当使用相应的结果时,您需要自己检查错误数组。
默认的错误处理(收集错误)保持不变,您可以按照上面描述的错误处理部分进行操作。
相关文章:
Node.JS多线程PromisePool之promise-pool库实现
什么是Promise Pool Map-like, concurrent promise processing for Node.js. Promise-Pool是一个用于管理并发请求的JavaScript库,它可以限制同时进行的请求数量,以避免过多的请求导致服务器压力过大。使用Promise-Pool可以方便地实现对多个异步操作的并…...
【C++】红黑树讲解及实现
前言: AVL树与红黑树相似,都是一种平衡二叉搜索树,但是AVL树的平衡要求太严格,如果要对AVL树做一些结构修改的操作性能会非常低下,比如:插入时要维护其绝对平衡,旋转的次数比较多,更…...
security如何不拦截websocket
只要添加一个关键配置就行 //忽略websocket拦截Overridepublic void configure(WebSecurity webSecurity){webSecurity.ignoring().antMatchers("/**");} 全部代码我放着了 package com.oddfar.campus.framework.config;import com.oddfar.campus.framework.secur…...
Unity类银河恶魔城学习记录12-3 p125 Limit Inventory Slots源代码
Alex教程每一P的教程原代码加上我自己的理解初步理解写的注释,可供学习Alex教程的人参考 此代码仅为较上一P有所改变的代码 【Unity教程】从0编程制作类银河恶魔城游戏_哔哩哔哩_bilibili Inventory.cs using Newtonsoft.Json.Linq; using System.Collections; us…...
【智能排班系统】雪花算法生成分布式ID
文章目录 雪花算法介绍起源与命名基本原理与结构优势与特点应用场景 代码实现代码结构自定义机器标识RandomWorkIdChooseLocalRedisWorkIdChooselua脚本 实体类SnowflakeIdInfoWorkCenterInfo 雪花算法类配置类雪花算法工具类 说明 雪花算法介绍 在复杂而庞大的分布式系统中&a…...
sass中的导入与部分导入
文章目录 sass中的导入与部分导入1. import:传统的导入方式2. use:现代化的模块化导入 sass中的导入与部分导入 在大型前端项目中,CSS代码量往往十分庞大,为了保持其可读性、可维护性以及便于团队协作,模块化开发成为…...
工业组态 物联网组态 组态编辑器 web组态 组态插件 编辑器
体验地址:by组态[web组态插件] BY组态是一款非常优秀的纯前端的【web组态插件工具】,可无缝嵌入到vue项目,react项目等,由于是原生js开发,对于前端的集成没有框架的限制。同时由于BY组态只是一个插件,不能独…...
git可视化工具
Gitkraken GitKraken 是一款专门用于管理和协作Git仓库的图形化界面工具。它拥有友好直观的界面,使得Git的操作变得更加简单易用,尤其适合那些不熟悉Git命令行的开发者。GitKraken提供了丰富的功能,如代码审查、分支管理、仓库克隆、提交、推…...
基于单片机电子密码锁系统设计
**单片机设计介绍,基于单片机电子密码锁系统设计 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序六、 文章目录 一 概要 基于单片机电子密码锁系统设计概要主要包括以下几个方面: 一、系统概述 基于单片机电子密码锁系统是一个…...
点云从入门到精通技术详解100篇-基于点云与图像纹理的 道路识别(续)
目录 3.1.2 图像滤波去噪 3.2 道路纹理特征提取 3.3 基于超像素分割的图像特征表达...
《机器学习在量化投资中的应用研究》目录
机器学习在量化投资中的应用研究 获取链接:机器学习在量化投资中的应用研究_汤凌冰著_北京:电子工业出版社 更多技术书籍:技术书籍分享,前端、后端、大数据、AI、人工智能... 内容简介 《机器学习在量化投资中的应用研究…...
Spring拓展点之SmartLifecycle如何感知容器启动和关闭
Spring为我们提供了拓展点感知容器的启动与关闭,从而使我们可以在容器启动或者关闭之时进行定制的操作。Spring提供了Lifecycle上层接口,这个接口只有两个方法start和stop两个方法,但是这个接口并不是直接提供给开发者做拓展点,而…...
深入理解Java匿名内部类(day21)
在Java编程中,匿名内部类是一种非常有用的特性,它允许我们定义和实例化一个类的子类或实现一个接口,而无需给出子类的名称。这种特性使得代码更加简洁、紧凑,尤其适用于一些只使用一次的临时对象。本文将深入探讨Java匿名内部类的…...
《状态模式(极简c++)》
本文章属于专栏- 概述 - 《设计模式(极简c版)》-CSDN博客 模式说明: 方案:状态模式是一种行为设计模式,用于在对象的内部状态发生改变时改变其行为。它包括三个关键角色:上下文(Context&#x…...
Day4-Hive直播行业基础笔试题
Hive笔试题实战 短视频 题目一:计算各个视频的平均完播率 有用户-视频互动表tb_user_video_log: id uid video_id start_time end_time if_follow if_like if_retweet comment_id 1 101 2001 2021-10-01 10:00:00 2021-10-01 10:00:30 …...
mybatis批量新增数据
数据量大的时候如果在循环中执行单条新增操作,是非常慢的。那么如何在mybatis中实现批量新增数据呢? 方法 insert 标签的 foreach 属性可以用于批量插入数据。您可以使用 foreach 属性遍历一个集合,并为集合中的每个元素生成一条插入语句。…...
webrtcP2P通话流程
文章目录 webrtcP2P通话流程webrtc多对多 mesh方案webrtc多对多 mcu方案webrtc多对多 sfu方案webrtc案例测试getUserMediagetUserMedia基础示例-打开摄像头getUserMedia canvas - 截图 打开共享屏幕 webrtcP2P通话流程 在这里,stun服务器包括stun服务和turn转发服…...
游戏引擎中的物理系统
一、物理对象与形状 1.1 对象 Actor 一般来说,游戏中的对象(Actor)分为以下四类: 静态对象 Static Actor动态对象 Dynamic Actor ---- 可能受到力/扭矩/冲量的影响检测器 TriggerKinematic Actor 运动学对象 ---- 忽略物理法则…...
【C++ STL有序关联容器】map 映射
文章目录 【 1. 基本原理 】【 2. map 的创建 】2.1 调用默认构造函数,创建一个空的 map2.2 map 被构造的同时初始化2.3 通过一个 queue 初始化另一个 queue2.4 取已建 map 中指定区域内的键值对,初始化新的 map2.5 指定排序规则 【 2. map 元素的操作 】…...
【ZZULIOJ】1041: 数列求和2(Java)
目录 题目描述 输入 输出 样例输入 Copy 样例输出 Copy code 题目描述 输入一个整数n,输出数列1-1/31/5-……前n项的和。 输入 输入只有一个整数n。 输出 结果保留2为小数,单独占一行。 样例输入 Copy 3 样例输出 Copy 0.87 code import java.util…...
使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式
一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明:假设每台服务器已…...
conda相比python好处
Conda 作为 Python 的环境和包管理工具,相比原生 Python 生态(如 pip 虚拟环境)有许多独特优势,尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处: 一、一站式环境管理:…...
基于大模型的 UI 自动化系统
基于大模型的 UI 自动化系统 下面是一个完整的 Python 系统,利用大模型实现智能 UI 自动化,结合计算机视觉和自然语言处理技术,实现"看屏操作"的能力。 系统架构设计 #mermaid-svg-2gn2GRvh5WCP2ktF {font-family:"trebuchet ms",verdana,arial,sans-…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...
循环冗余码校验CRC码 算法步骤+详细实例计算
通信过程:(白话解释) 我们将原始待发送的消息称为 M M M,依据发送接收消息双方约定的生成多项式 G ( x ) G(x) G(x)(意思就是 G ( x ) G(x) G(x) 是已知的)࿰…...
理解 MCP 工作流:使用 Ollama 和 LangChain 构建本地 MCP 客户端
🌟 什么是 MCP? 模型控制协议 (MCP) 是一种创新的协议,旨在无缝连接 AI 模型与应用程序。 MCP 是一个开源协议,它标准化了我们的 LLM 应用程序连接所需工具和数据源并与之协作的方式。 可以把它想象成你的 AI 模型 和想要使用它…...
Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务
通过akshare库,获取股票数据,并生成TabPFN这个模型 可以识别、处理的格式,写一个完整的预处理示例,并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务,进行预测并输…...
智能在线客服平台:数字化时代企业连接用户的 AI 中枢
随着互联网技术的飞速发展,消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁,不仅优化了客户体验,还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用,并…...
[ICLR 2022]How Much Can CLIP Benefit Vision-and-Language Tasks?
论文网址:pdf 英文是纯手打的!论文原文的summarizing and paraphrasing。可能会出现难以避免的拼写错误和语法错误,若有发现欢迎评论指正!文章偏向于笔记,谨慎食用 目录 1. 心得 2. 论文逐段精读 2.1. Abstract 2…...
微信小程序 - 手机震动
一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注:文档 https://developers.weixin.qq…...
