Untitled

 avatar
unknown
plain_text
a year ago
1.4 kB
2
Indexable
/**
 * Makes parallel HTTP requests to the given array of URLs, with a constraint on the number
 * of simultaneous requests allowed. Once all requests are completed, calls the provided
 * callback function with an array of text responses in the same order as the input URLs.
 *
 * @param {string[]} urls - An array of URLs to make HTTP requests to.
 * @param {number} limit - The maximum number of simultaneous HTTP requests allowed.
 * @param {function(string[]): void} callback - The callback function to be called with an
 * array of text responses once all requests are completed.
 */
function parallelHttpRequests(urls, limit, callback) {
    let currentRequests = 0;
    let sendingRequest = 0;
    const mutateUrls =  [...urls];
    const results = [];

    if (urls.length === 0) return -1;

    const  makeRequest = function (url, index) {
        if (currentRequests > urls.length) {
            return;
        }
        currentRequests++

        return fetch(url).then(result => {
            results[index] = result
            sendingRequest++
        }).finally(() => {
            if (sendingRequest === urls.length) {
                callback(results)
            } else {
                return makeRequest(urls[currentRequests], currentRequests)
            }

        })
    }

    for (let i = 0; i < limit; i++) {
        makeRequest(urls[i], index)
    }


    callback()
}


Leave a Comment