4.3.0 • Published 6 months ago

als-smart-promise v4.3.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

als-smart-promise

Description

SmartPromise is a versatile utility for managing chains of asynchronous or synchronous functions. Its features include:

  • Sequential execution of functions in a defined order.
  • Global (static) chain shared across all instances.
  • Instance-level chains for specific tasks.
  • Flexible control with once and last flags.
  • Timeout support to limit execution time.
  • Linking chains to create complex hierarchies of execution.
  • Flow control with next, resolve, and reject.
  • Sync/Async support Automatically detects whether the chain contains asynchronous functions and switches between synchronous and asynchronous execution.

SmartPromise is ideal for orchestrating tasks with predictable flow, combining global and instance-specific logic, and handling edge cases like timeouts or early resolution.

Installation

Install via npm:

npm install smart-promise

Basic Usage

Example: Sequential Execution

The execute method dynamically determines whether the chain contains asynchronous functions and executes them accordingly. If all functions are synchronous, it will return the result immediately; otherwise, it returns a Promise.

const SmartPromise = require('als-smart-promise');
const name = 'some', timeout = null;
const chain = new SmartPromise(timeout,name);

chain.use(({ next }) => {
  console.log('Step 1');
  next();
});

chain.use(({ next }) => {
  console.log('Step 2');
  next();
});

chain.execute() // Automatically handles synchronous execution

Output:

Step 1
Step 2
Chain completed

Example: Resolving the Chain

const chain = new SmartPromise();

chain.use(({ next }) => {
  console.log('Before resolving');
  next('Final Result');
});

chain.use(async ({ resolve, result }) => {
  console.log('This won’t run because the chain was resolved:', result);
  resolve();
});

// Even if synchronous, the chain will resolve correctly with the final result.
chain.execute().then((result) => {
  console.log('Resolved with:', result);
});

Output:

Before resolving
Resolved with: Final Result

Advanced Usage

Global (Static) Chain

Static functions are added with SmartPromise.use() and apply to all instances:

SmartPromise.use(({ next }) => {
  console.log('Global function');
  next();
});

const chain = new SmartPromise();
chain.use(({ next }) => {
  console.log('Instance function');
  next();
});

chain.execute().then(() => {
  console.log('Done');
});

Output:

Global function
Instance function
Done

Using last

Functions marked as last run after all others:

const chain = new SmartPromise();

chain.use(({ next }) => {
  console.log('Step 1');
  next();
});

chain.use(({ next }) => {
  console.log('Step 3 (last)');
  next();
}, { last: true });

chain.use(({ next }) => {
  console.log('Step 2');
  next();
});

chain.execute();

Output:

Step 1
Step 2
Step 3 (last)

Timeout Handling

const chain = new SmartPromise(100);

chain.use(async ({ next }) => {
  await new Promise((r) => setTimeout(r, 200)); // Simulate delay
  next();
});

chain.execute()
  .then(() => {
    console.log('Completed in time');
  })
  .catch((err) => {
    console.error(err.message); // "Promise timeout 100"
  });

Linking Chains

Chains can link other chains, combining their logic:

const chain1 = new SmartPromise();
const chain2 = new SmartPromise();

chain1.use(({ next }) => {
  console.log('Chain 1 - Step 1');
  next();
});

chain2.use(({ next }) => {
  console.log('Chain 2 - Step 1');
  next();
});

chain1.link(chain2);

chain1.execute().then(() => {
  console.log('Both chains executed');
});

Output:

Chain 1 - Step 1
Chain 2 - Step 1
Both chains executed

Resolving in Linked Chains

const chain1 = new SmartPromise();
const chain2 = new SmartPromise();

chain1.use(({ next }) => {
  console.log('Chain 1 - Before resolve');
  next('Final Result');
});

chain2.use(({ resolve }) => {
  console.log('Chain 2 - Won’t run');
  resolve();
});

chain1.link(chain2);

chain1.execute().then((result) => {
  console.log('Resolved with:', result);
});

Output:

Chain 1 - Before resolve
Resolved with: Final Result

API Reference

class SmartPromise

Creates an instance of SmartPromise.

  • Parameters:
    • timeout (optional): Time in milliseconds to reject the chain if not completed.
    • name (optional): addede as this.name and will appear as part of context

SmartPromise.chain (static)

Global shared chain of functions. Functions here are executed before instance-level functions.


SmartPromise.use(fn, options = {}) (static)

Adds a function to the global chain.

  • Parameters:
    • fn: A function with signature ({ next, resolve, reject, result }, ...args).
    • options:
      • once: Removes the function after the first execution.
      • last: Executes the function after all others.

use(fn, options = {})

Adds a function to the instance’s chain.


link(chain)

Links another SmartPromise chain.

  • Parameters:
    • chain: Another SmartPromise instance to link.

execute(...args)

Executes all functions in the chain. If the chain contains only synchronous functions, it returns the result directly. Otherwise, it returns a Promise.

  • Returns: A result or Promise that resolves with the final result.

  • Example:

const chain = new SmartPromise();
chain.use(async ({ resolve }) => resolve('Done!'));
chain.execute().then(console.log); // "Done!"

delete(fn)

Removes a function from the instance and global chains.

4.3.0

6 months ago

4.1.0

6 months ago

4.0.0

6 months ago

4.2.0

6 months ago

3.0.0

1 year ago

2.1.0

1 year ago

2.0.0

1 year ago

1.1.0

2 years ago

1.0.0

2 years ago