What is map-limit?
The map-limit npm package allows you to map over an array of items with a limit on the number of concurrent asynchronous operations. This is useful for controlling the rate of operations, especially when dealing with APIs or other resources that have rate limits.
Basic Usage
This example demonstrates the basic usage of map-limit. It processes an array of numbers, doubling each one, but only allows two asynchronous operations to run concurrently.
const mapLimit = require('map-limit');
const tasks = [1, 2, 3, 4, 5];
const limit = 2;
function asyncTask(item, callback) {
setTimeout(() => {
callback(null, item * 2);
}, 1000);
}
mapLimit(tasks, limit, asyncTask, (err, results) => {
if (err) throw err;
console.log(results); // [2, 4, 6, 8, 10]
});
Error Handling
This example shows how to handle errors in map-limit. If an error occurs during the processing of an item, it is passed to the final callback.
const mapLimit = require('map-limit');
const tasks = [1, 2, 3, 4, 5];
const limit = 2;
function asyncTask(item, callback) {
setTimeout(() => {
if (item === 3) {
callback(new Error('An error occurred'));
} else {
callback(null, item * 2);
}
}, 1000);
}
mapLimit(tasks, limit, asyncTask, (err, results) => {
if (err) {
console.error(err.message); // 'An error occurred'
} else {
console.log(results);
}
});