node.js - Async + Axios - 速率控制

标签 node.js asynchronous axios

我目前使用 promise 向 API 发送 GET 请求 200 次。毫不奇怪,在如此短的时间内允许的最大连接数。

我正在使用 axios 来执行此操作:

const memberPromises = members.map(member => axios.get(`players/%23${member.tag}`))

axios.all().then().catch() // etc

..其中成员最多可以有 200 个元素。

似乎没有办法在 axios 中对这些请求进行本地速率控制,但我将如何使用 async(或其他库,如果有更好的) ) queue 方法带有 concurrent 参数来限制同时请求的数量?

最佳答案

这个怎么样?

将成员映射到 promise ,超时后解决 promise

let RATE_LIMIT_BASE = 100; //100ms separation

let promises = members.map((member, idx) => {
    return new Promise((resolve, reject) => {
        setTimeout(
            () =>
                axios
                    .get(`players/%23${member.tag}`)
                    .then(res => resolve(res))
                    .catch(err => reject(err)),
            RATE_LIMIT_BASE * idx
        );
    });
});

Promise.all(promises).then().catch(); // etc;

在评论中,正如marvel308所说,

this could fail in certain cases, since setTimeout just guarantees that the code will execute atleast 100ms after setTimeout is called, they could still queue up in the event queue in case some CPU intensive task was blocking the call stack

感谢 marvel308 的建议

关于node.js - Async + Axios - 速率控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45676307/

相关文章:

c# - 如何使用 Azure TableClient 2.0 BeginExecuteQuerySegmented

javascript - 重构破坏初始状态

node.js - Grunt 安装错误 : "should be installed with -g"

javascript - 如何在新行中将 JS 对象推送到 JSON?

javascript - 我可以在 javascript 中强制解决等待结果的 promise 吗?

javascript - NodeJS 无法异步发出 GET 请求

reactjs - 使用动态路由、next JS 和 useEffect 在 React 中获取数据

javascript - 如何在 TypeScript 中使用包含的 Axios 类型定义进行依赖注入(inject)

javascript - 创建 Node-Red 自定义 Node : config not working, 显示文本框而不是配置下拉列表

node.js - Mongoose 实例 .save() 不工作