Promise Throttle 使用教程
1、项目介绍
Promise Throttle
是一个轻量级(约530B压缩后)的依赖库,旨在限制每单位时间内执行的 Promise 数量。这对于避免在使用 REST API 时达到速率限制非常有用。该库可以在服务器端和浏览器中使用,并且支持自定义 Promise 库。
2、项目快速启动
安装
Node.js 环境
npm install promise-throttle
浏览器环境
bower install promise-throttle
使用示例
以下是一个简单的使用示例,展示了如何在 Node.js 环境中使用 Promise Throttle
来限制 Promise 的执行速率。
// 引入 Promise Throttle 库
var PromiseThrottle = require('promise-throttle');
// 定义一个返回 Promise 的函数
var myFunction = function(i) {
return new Promise(function(resolve, reject) {
// 模拟异步操作
setTimeout(function() {
console.log(i + ": " + Math.random());
resolve(i);
}, 10);
});
};
// 创建 PromiseThrottle 实例
var promiseThrottle = new PromiseThrottle({
requestsPerSecond: 1, // 每秒最多执行 1 个请求
promiseImplementation: Promise // 使用的 Promise 库
});
// 定义需要执行的 Promise 数量
var amountOfPromises = 10;
// 添加 Promise 到 Throttle 中
while (amountOfPromises-- > 0) {
promiseThrottle.add(myFunction.bind(this, amountOfPromises))
.then(function(i) {
console.log("Promise " + i + " done");
});
}
3、应用案例和最佳实践
应用案例
避免 API 速率限制
在使用第三方 REST API 时,通常会有速率限制。通过使用 Promise Throttle
,可以确保在单位时间内不会超过 API 的速率限制,从而避免被封禁或限制访问。
动态调整速率
Promise Throttle
支持通过 weight
选项动态调整每个 Promise 的速率。例如,某些操作可能比其他操作更“重”,可以通过设置 weight
来调整其速率。
var regularAction = promiseThrottle.add(performRegularCall);
var heavyAction = promiseThrottle.add(performHeavyCall, {weight: 2});
最佳实践
使用 AbortSignal 取消 Promise
在某些情况下,可能需要取消正在排队的 Promise。Promise Throttle
支持使用 AbortSignal
来取消 Promise。
var controller = new AbortController();
var signal = controller.signal;
var pt = createPromiseThrottle(10);
pt.addAll([
function() { return fetch('example.com/a'); },
function() { return fetch('example.com/b'); },
function() { return fetch('example.com/c'); }
], {signal: signal})
.catch(function(e) {
if (e.name === 'AbortError') {
console.log('Promises aborted');
}
});
// 取消 Promise
controller.abort();
4、典型生态项目
ivasilov/promised-twitter
promised-twitter
是一个使用 Promise
封装的 Twitter API 客户端库。通过结合 Promise Throttle
,可以有效地管理 Twitter API 的速率限制。
JMPerez/spotify-dedup
spotify-dedup
是一个用于去重 Spotify 播放列表的工具。在使用 Spotify API 时,Promise Throttle
可以帮助避免速率限制问题。
johannesss/randify
randify
是一个用于生成随机音乐播放列表的工具。通过使用 Promise Throttle
,可以确保在访问音乐 API 时不会超过速率限制。
JoseBarrios/mturk-api
mturk-api
是一个用于访问 Amazon Mechanical Turk API 的库。结合 Promise Throttle
,可以有效地管理 API 请求的速率。
zackiles/lucy-bot
lucy-bot
是一个用于构建聊天机器人的工具。在使用第三方 API 时,Promise Throttle
可以帮助避免速率限制问题。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考