async.eachOfLimit不会将我的http请求数限制为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('')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
});
}
我使用async.eachOfLimit将请求数限制为10但是当我运行他从1到20打印的代码时它不起作用我也尝试调用回调但我得到的回调不是函数我怎么解决它并将请求限制为只有10个并发感谢
回答如下:您正在使用回调混合async / await编码。当您使用async.js库时,makeRequest
函数必须是:
- 一个调用回调的普通函数
- 标记为“async”的函数,它返回一个promise。
如果函数标记为“async”,则async.js不会将callback
参数传递给它。相反,它只会等待承诺解决。
在你的代码中,实际上没有什么必须是“异步”。你可以在任何地方使用回调。
这是一个工作片段:
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?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
callback();
});
}
async.eachOfLimit不会将我的http请求数限制为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('')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
});
}
我使用async.eachOfLimit将请求数限制为10但是当我运行他从1到20打印的代码时它不起作用我也尝试调用回调但我得到的回调不是函数我怎么解决它并将请求限制为只有10个并发感谢
回答如下:您正在使用回调混合async / await编码。当您使用async.js库时,makeRequest
函数必须是:
- 一个调用回调的普通函数
- 标记为“async”的函数,它返回一个promise。
如果函数标记为“async”,则async.js不会将callback
参数传递给它。相反,它只会等待承诺解决。
在你的代码中,实际上没有什么必须是“异步”。你可以在任何地方使用回调。
这是一个工作片段:
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?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
callback();
});
}