async.eachOfLimit 不是限制我的 http 请求数为 10
async.eachOfLimit is not limit my number of http request to 10
const unirest = require('unirest');
const async = require('async');
let count = 0;
let ids = [];
(async () => {
for (let index = 1; index <= 20; index++) {
ids.push(index);
}
async.eachOfLimit(ids, 10, makeRequest, function (err) {
if (err) throw err;
});
})();
async function makeRequest(index, callback) {
console.log(index);
await unirest.get('https://api.ipify.org?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
});
}
我正在使用 async.eachOfLimit 将请求数限制为 10,但它不起作用
当我 运行 他从 1 打印到 20 的代码时
我也尝试调用 callback 但我得到的 callback is not a function
我如何解决它并将请求限制为只有 10 个并发
谢谢
您将 async/await 编码与回调混合在一起。当您使用 async.js 库时,makeRequest
函数必须是:
- 调用回调的普通函数
- 标记为 'async' 的函数 returns 一个承诺。
如果函数被标记为 'async',async.js 将不会将 callback
参数传递给它。相反,它只会等待解决承诺。
在您的代码中,实际上没有什么必须 'async'。您可以在任何地方使用回调。
这是一个工作片段:
const unirest = require('unirest');
const async = require('async');
let count = 0;
let ids = [];
for (let index = 1; index <= 20; index++) {
ids.push(index);
}
async.eachOfLimit(ids, 10, makeRequest, function (err) {
if (err) throw err;
});
function makeRequest(item, index, callback) {
console.log(item);
unirest.get('https://api.ipify.org?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
callback();
});
}
const unirest = require('unirest');
const async = require('async');
let count = 0;
let ids = [];
(async () => {
for (let index = 1; index <= 20; index++) {
ids.push(index);
}
async.eachOfLimit(ids, 10, makeRequest, function (err) {
if (err) throw err;
});
})();
async function makeRequest(index, callback) {
console.log(index);
await unirest.get('https://api.ipify.org?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
});
}
我正在使用 async.eachOfLimit 将请求数限制为 10,但它不起作用 当我 运行 他从 1 打印到 20 的代码时 我也尝试调用 callback 但我得到的 callback is not a function 我如何解决它并将请求限制为只有 10 个并发 谢谢
您将 async/await 编码与回调混合在一起。当您使用 async.js 库时,makeRequest
函数必须是:
- 调用回调的普通函数
- 标记为 'async' 的函数 returns 一个承诺。
如果函数被标记为 'async',async.js 将不会将 callback
参数传递给它。相反,它只会等待解决承诺。
在您的代码中,实际上没有什么必须 'async'。您可以在任何地方使用回调。
这是一个工作片段:
const unirest = require('unirest');
const async = require('async');
let count = 0;
let ids = [];
for (let index = 1; index <= 20; index++) {
ids.push(index);
}
async.eachOfLimit(ids, 10, makeRequest, function (err) {
if (err) throw err;
});
function makeRequest(item, index, callback) {
console.log(item);
unirest.get('https://api.ipify.org?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
callback();
});
}