What is pend?
The pend npm package is designed to manage and limit the concurrency of asynchronous operations in Node.js applications. It provides a simple API to queue tasks and control how many of them are executed in parallel, making it easier to manage resources and improve the performance of applications that perform a lot of asynchronous operations, such as file I/O or network requests.
Limiting concurrency of asynchronous operations
This code sample demonstrates how to use pend to limit the concurrency of asynchronous operations. It creates a new Pend instance, sets a concurrency limit, and then queues several asynchronous operations. Pend ensures that only a specified number of operations run in parallel, and provides a callback for when all operations are completed.
const Pend = require('pend');
const pend = new Pend();
pend.max = 2; // Limit to 2 concurrent operations
function asyncOperation(callback) {
setTimeout(() => {
console.log('Operation completed');
callback();
}, 1000);
}
for (let i = 0; i < 5; i++) {
pend.go((cb) => {
asyncOperation(cb);
});
}
pend.wait(() => {
console.log('All operations completed');
});