What is the best way to limit concurrency when using ES6's Promise.all()?

前端 未结 17 606
执念已碎
执念已碎 2020-11-29 21:28

I have some code that is iterating over a list that was queried out of a database and making an HTTP request for each element in that list. That list can sometimes be a rea

17条回答
  •  有刺的猬
    2020-11-29 21:52

    It can be resolved using recursion.

    The idea is that initially you send maximum allowed number of requests and each of these requests should recursively continue to send itself on its completion.

    function batchFetch(urls, concurrentRequestsLimit) {
        return new Promise(resolve => {
            var documents = [];
            var index = 0;
    
            function recursiveFetch() {
                if (index === urls.length) {
                    return;
                }
                fetch(urls[index++]).then(r => {
                    documents.push(r.text());
                    if (documents.length === urls.length) {
                        resolve(documents);
                    } else {
                        recursiveFetch();
                    }
                });
            }
    
            for (var i = 0; i < concurrentRequestsLimit; i++) {
                recursiveFetch();
            }
        });
    }
    
    var sources = [
        'http://www.example_1.com/',
        'http://www.example_2.com/',
        'http://www.example_3.com/',
        ...
        'http://www.example_100.com/'
    ];
    batchFetch(sources, 5).then(documents => {
       console.log(documents);
    });
    

提交回复
热议问题