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 ,但是我得到的回调不是函数 我该如何解决并将请求限制为仅10个并发 谢谢
答案 0 :(得分:0)
您正在将异步/等待编码与回调混合在一起。当您使用 async.js 库时,makeRequest
函数要么必须是:
如果该函数被标记为'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.org?format=json')
.headers({ 'Content-Type': 'application/json' })
.end(async (response) => {
console.log(response.body);
callback();
});
}