als-promises
Change log for v2
- Code refactoring and improvement
- Getters and setters for default batch size
Overview
The Promises
function is designed to manage and optimize the execution of a large number of asynchronous operations, such as promises, by batching them. This approach is particularly useful for scenarios involving resource-intensive tasks, like file operations or network requests, where you need to avoid overloading the system.
Browser Compatibility
The Promises
function is compatible with most modern web browsers. This includes the latest versions of Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge. The function uses ECMAScript 6 (ES6) features like async/await, which are widely supported in these browsers.
Functionality
- Batches Asynchronous Operations: The function groups promises into batches to limit the number of concurrent operations.
- Queue Management: It uses an internal queue to manage these batches, ensuring that each batch is processed sequentially.
- Error Handling: The function handles errors gracefully. If a promise within a batch fails, it does not stop the processing of other promises in the same batch.
- Results and Errors: The function returns an object containing two arrays: one for successful results and another for errors.
Usage
const promises = require('als-promises')
// <script src="/node_modules/als-promises/promises.js"></script> for browser
// Getters and setters
promises.defSize = 30
promises.defSize // 30 (default is 100)
promises.queue
promises.inProgress
// Usage
promises(arrayOfPromises,batchSize,results,errors) // returns promise
Validation
The function includes validation checks to ensure that:
-
promises
is an array. -
batchSize
is a positive number. -
results
anderrors
are arrays, if provided.
These checks help in avoiding common mistakes and ensure smooth functioning of the batch processing.
Getters and Setters
The function provides getters and setters for managing its internal state:
-
defSize
: Get or set the default batch size.- This value is used as the default number of promises to process simultaneously within a batch. Adjusting this value can be useful for tuning performance based on the specific nature of the tasks and system capabilities.
-
queue
: Get the current state of the queue, including pending batches. -
inProgress
: Determine if the processing is currently active.
These properties can be accessed and modified as needed to adjust the behavior of the function dynamically.
Parameters
-
promises
: An array of functions that return promises. These functions are executed to generate the promises. -
batchSize
(optional, default = 100): The maximum number of promises to process simultaneously within a batch. This value can be adjusted with thedefSize
setter. -
results
(optional): An array to store the results of successfully resolved promises. -
errors
(optional): An array to store the errors from rejected promises.
Returns
- The function returns a promise that resolves to an object with the following structure:
-
results
: An array containing the results of successfully resolved promises. -
errors
: An array containing the errors from promises that were rejected.
-
Example
const fetchPromises = urls.map(url => () => fetch(url));
promises(fetchPromises, 10)
.then(({ results, errors }) => {
console.log('Fetched data:', results);
console.error('Errors:', errors);
})
.catch(error => {
console.error('Unexpected error:', error);
});
In this example, fetchPromises
is an array of functions returning promises from the fetch
API, and we are processing these promises in batches of 10. The final result includes arrays of fetched data (results
) and any errors (errors
) that occurred during fetching.
Handling Nested Promises
When using nested promises, it's important to understand how these nested callsto ensure that promises are managed correctly without leading to deadlock or exceeding the intended concurrency limitations.
Correct Usage
Example: Independent Operations
In scenarios where nested operations are independent and do not need to wait for each other, you can safely nest promises
calls.
const batch1 = [asyncOperation1, asyncOperation2];
const batch2 = [asyncOperation3, asyncOperation4];
const outerPromise = promises([
promises(batch1), // First nested call
promises(batch2) // Second nested call
], 2);
// This setup is safe because batch1 and batch2 are independent.
In this example, batch1
and batch2
are independent, and thus their concurrency is managed separately without risk of deadlock.
Incorrect Usage
Example: Interdependent Operations Leading to Deadlock
If nested promises
calls are interdependent and one depends on the completion of the other, this can lead to a deadlock.
let resolveOuter;
const outerPromise = new Promise(resolve => {
resolveOuter = resolve;
});
const innerPromise = promises([() => outerPromise]);
const deadlockPromise = promises([
() => innerPromise,
() => new Promise(resolve => resolveOuter(resolve))
], 1);
// This setup can lead to a deadlock as innerPromise waits for outerPromise,
// which in turn is resolved in the second call within deadlockPromise.
In this example, a deadlock occurs because innerPromise
is waiting for outerPromise
to resolve, which only happens in the second promise within deadlockPromise
.
Notes
-
Performance Considerations: The optimal
batchSize
can vary based on the specific requirements and system constraints. It may require tuning for optimal performance. - Error Handling: Errors are segregated and do not halt the processing of the entire batch, allowing for the successful completion of other operations.