als-smart-promise
is a JavaScript utility for managing and executing chains of asynchronous functions with advanced error handling and support for timeouts. It is built to provide a flexible way to create and manage sequences of operations where each step in the sequence can depend on the result of the previous one.
- args is a first parameter and not context
npm install als-smart-promise
Here's a basic example of how to use als-smart-promise
:
const SmartPromise = require('als-smart-promise');
// Define your asynchronous functions
const func1 = async (args,context) => {
// Your code here
context.next('result of func1');
};
const func2 = async (args,context, resultFromFunc1) => {
// Your code here
context.resolve('final result');
};
// Create a SmartPromise instance
const sp = new SmartPromise([func1, func2]);
// Run the sequence
sp.run().then(result => {
console.log(result); // 'final result'
}).catch(error => {
console.error(error);
});
-
fns
: Array of functions to be executed in sequence. -
args
: Initial arguments stored as args in instance and available ascontext.args
. -
errors
: An array to store any errors that occur during the execution of the functions.
-
lastResult
: Stores the result of the last executed function. -
errors
: Array of errors caught during the execution of the chain. -
args
: Stores args from constructor
Executes the chain of functions.
-
timeout
: Optional. A number representing the timeout in milliseconds. If the chain does not complete within this time, it is rejected with a timeout error.
als-smart-promise
captures errors thrown in any function in the chain and pushes them to the errors
array. The chain continues to execute unless manually stopped using context.reject()
.
The run
method accepts an optional timeout
parameter. If the chain of functions does not resolve or reject before the timeout, the promise is rejected with a timeout error.
const sp = new SmartPromise([func1, func2]);
sp.run(1000).then(result => {
console.log(result);
}).catch(error => {
console.error(error); // 'Promise timeout 1000' if timed out
});