The Map Async question introduced a function that accepts an array of items, maps each element with an asynchronous mapping function, and returns a Promise that resolves to the mapped results.
In practice, this can be used to map an input array to API results, where each input element becomes the API argument. However, a large input array would make that many API calls at the same time, which will almost certainly cause the API service to rate-limit the caller. The goal is to execute tasks concurrently for efficiency while staying within the API's rate limits.
Implement a mapAsyncLimit function that takes an optional size parameter, which is the maximum number of ongoing async tasks, so the input array can be processed in chunks of size, achieving parallelism while staying within the provided limit. If size is not specified, the chunk size is unlimited.
async function fetchUpperCase(q: string) {// Fake API service that converts a string to uppercase.const res = await fetch('https://uppercase.com?q=' + encodeURIComponent(q));return await res.text();}// Only a maximum of 2 pending requests at any time.const results = await mapAsyncLimit(['foo', 'bar', 'qux', 'quz'],fetchUpperCase,2,);console.log(results); // ['FOO', 'BAR', 'QUX', 'QUZ'];
console.log() statements will appear here.