CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-q

A comprehensive promise library implementing CommonJS Promises/A,B,D specifications for JavaScript

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

flow-control.mddocs/

Flow Control and Timing

Utilities for controlling promise execution timing, delays, timeouts, conditional processing, and managing asynchronous flow.

Capabilities

Delay Operations

Creates promises that resolve after a specified time delay.

/**
 * Returns promise that resolves after specified milliseconds
 * @param object - Value to resolve with after delay
 * @param timeout - Delay in milliseconds
 * @returns Promise that resolves to object after timeout
 */
function Q.delay(object, timeout);

/**
 * Delays fulfillment by specified milliseconds
 * @param ms - Delay duration in milliseconds
 * @returns Promise that resolves to same value after delay
 */
promise.delay(ms);

Usage Examples:

const Q = require("q");

// Static delay with value
Q.delay("Hello after 1 second", 1000)
  .then(message => console.log(message));

// Instance delay
Q.resolve("Immediate value")
  .delay(500)
  .then(value => console.log("Delayed:", value));

// Delay in promise chain
fetchUserData()
  .then(user => {
    console.log("Processing user:", user.name);
    return user;
  })
  .delay(1000) // Wait 1 second before next step
  .then(user => sendWelcomeEmail(user));

// Creating delays without values
Q.delay(2000).then(() => {
  console.log("2 seconds have passed");
});

Timeout Operations

Rejects promises if they don't resolve within a specified time limit.

/**
 * Rejects promise if not fulfilled before timeout
 * @param object - Promise or value to timeout
 * @param ms - Timeout duration in milliseconds
 * @param message - Optional custom timeout message
 * @returns Promise that rejects if timeout exceeded
 */
function Q.timeout(object, ms, message);

/**
 * Rejects if not fulfilled within timeout
 * @param ms - Timeout duration in milliseconds  
 * @param message - Optional custom timeout message
 * @returns Promise that rejects on timeout
 */
promise.timeout(ms, message);

Usage Examples:

const Q = require("q");

// Static timeout
Q.timeout(slowOperation(), 5000, "Operation took too long")
  .then(result => console.log("Completed:", result))
  .catch(error => console.error("Error:", error.message));

// Instance timeout
fetchDataFromAPI()
  .timeout(3000, "API request timed out")
  .then(data => processData(data))
  .catch(error => {
    if (error.message.includes("timed out")) {
      return getDataFromCache();
    }
    throw error;
  });

// Timeout with race pattern
function timeoutPromise(promise, ms) {
  return Q.race([
    promise,
    Q.delay(ms).then(() => {
      throw new Error(`Operation timed out after ${ms}ms`);
    })
  ]);
}

Conditional Processing

Handles conditional promise processing and value-based branching.

/**
 * Conditional promise handling with optional timing estimate
 * @param value - Value or promise to process
 * @param fulfilled - Callback for successful resolution
 * @param rejected - Optional callback for rejection
 * @param ms - Optional timing estimate
 * @returns Promise for conditional result
 */
function Q.when(value, fulfilled, rejected, ms);

/**
 * Resolves to value if both promises fulfill to same value
 * @param x - First promise or value
 * @param y - Second promise or value  
 * @returns Promise that resolves if both values are equal
 */
function Q.join(x, y);

Usage Examples:

const Q = require("q");

// Conditional processing with Q.when
function processInput(input) {
  return Q.when(input,
    value => {
      if (typeof value === "string") {
        return value.toUpperCase();
      }
      return String(value);
    },
    error => {
      console.error("Input processing failed:", error);
      return "DEFAULT";
    }
  );
}

// Join operation for equality checking
const user1Promise = fetchUser(1);
const user2Promise = fetchUser(2);

Q.join(
  user1Promise.then(u => u.department),
  user2Promise.then(u => u.department)
).then(department => {
  console.log("Both users are in department:", department);
}).catch(() => {
  console.log("Users are in different departments");
});

// Complex conditional flow
function handleUserAction(userId, action) {
  return Q.when(validateUser(userId),
    user => {
      if (user.permissions.includes(action)) {
        return performAction(user, action);
      } else {
        throw new Error("Insufficient permissions");
      }
    },
    error => {
      console.error("User validation failed:", error);
      return logUnauthorizedAttempt(userId, action);
    }
  );
}

Finally Operations

Executes cleanup code regardless of promise resolution or rejection.

/**
 * Executes callback regardless of fulfillment or rejection
 * @param callback - Function to execute for cleanup
 * @param ms - Optional timing estimate
 * @returns Promise that preserves original result
 */
promise.finally(callback, ms);

Usage Examples:

const Q = require("q");

// Resource cleanup
function processFile(filename) {
  let fileHandle;
  
  return openFile(filename)
    .then(handle => {
      fileHandle = handle;
      return processFileContents(handle);
    })
    .finally(() => {
      if (fileHandle) {
        closeFile(fileHandle);
        console.log("File closed");
      }
    });
}

// Loading state management
function fetchUserData(userId) {
  showLoadingSpinner();
  
  return apiClient.getUser(userId)
    .then(user => {
      updateUserInterface(user);
      return user;
    })
    .catch(error => {
      showErrorMessage(error.message);
      throw error;
    })
    .finally(() => {
      hideLoadingSpinner();
    });
}

// Database transaction cleanup
function updateUserRecord(userId, data) {
  let transaction;
  
  return database.beginTransaction()
    .then(tx => {
      transaction = tx;
      return transaction.update("users", userId, data);
    })
    .then(result => {
      return transaction.commit().then(() => result);
    })
    .catch(error => {
      if (transaction) {
        return transaction.rollback().then(() => {
          throw error;
        });
      }
      throw error;
    })
    .finally(() => {
      console.log("Transaction completed");
    });
}

Value Transformation

Methods for transforming promise values regardless of original outcome.

/**
 * Resolves to specific value regardless of original result
 * @param value - Value to resolve with
 * @returns Promise that resolves to the specified value
 */
promise.thenResolve(value);

/**
 * Rejects with specific error regardless of original result  
 * @param error - Error to reject with
 * @returns Promise that rejects with the specified error
 */
promise.thenReject(error);

Usage Examples:

const Q = require("q");

// Transform success to specific value
fetchUserPreferences()
  .thenResolve("preferences loaded")
  .then(message => console.log(message));

// Transform any outcome to error
riskyOperation()
  .thenReject(new Error("Operation deprecated"))
  .catch(error => console.error(error.message));

// Conditional transformation
function processWithFallback(data) {
  return validateData(data)
    .then(valid => valid ? data : null)
    .catch(() => null)
    .then(result => {
      if (result === null) {
        return Q.resolve().thenResolve("default data");
      }
      return result;
    });
}

Install with Tessl CLI

npx tessl i tessl/npm-q

docs

advanced.md

collections.md

core-promises.md

flow-control.md

functional.md

index.md

nodejs.md

promise-chains.md

property-access.md

queue.md

state-inspection.md

tile.json