Suhaib Abu shawesh
Suhaib Abu shawesh

Reputation: 150

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);
        });
}

I am using async.eachOfLimit to limit number of request to 10 but it doesn't work when I run the code he print from 1 to 20 also I am try to call the callback but i get callback is not a function How I can solve it and limit the request to only 10 concurrency thanks

Upvotes: 1

Views: 1626

Answers (1)

Azami
Azami

Reputation: 2161

You are mixing async/await coding with callbacks. When you use the async.js library, the makeRequest function either has to be:

  1. A normal function that calls a callback
  2. A function labeled as 'async' that returns a promise.

If the function is labeled as 'async', async.js will not pass the callback argument to it. Instead, it will just wait for a promise to resolve.

In your code, nothing actually had to be 'async'. You could just use callbacks everywhere.

Here is a working snippet:

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();
        });
}

Upvotes: 2

Related Questions