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

state-inspection.mddocs/

Promise State and Inspection

Methods for examining promise state, extracting information about promise fulfillment status, and runtime type checking.

Capabilities

Promise Type Testing

Functions for determining if objects are Q promises and checking promise-like behavior.

/**
 * Tests if object is a Q promise
 * @param object - Object to test
 * @returns True if object is a Q promise
 */
function Q.isPromise(object);

Usage Examples:

const Q = require("q");

// Test different object types
const regularPromise = Q.resolve("value");
const nativePromise = Promise.resolve("native");
const thenable = { then: (resolve) => resolve("thenable") };
const regularObject = { value: "not a promise" };

console.log(Q.isPromise(regularPromise)); // true
console.log(Q.isPromise(nativePromise));  // false (not a Q promise)
console.log(Q.isPromise(thenable));       // false (thenable but not Q promise)
console.log(Q.isPromise(regularObject));  // false

// Use in conditional logic
function handleInput(input) {
  if (Q.isPromise(input)) {
    return input.then(value => processValue(value));
  } else {
    return Q.resolve(processValue(input));
  }
}

// Type checking in error handling
function safeProcess(maybePromise) {
  try {
    if (Q.isPromise(maybePromise)) {
      return maybePromise.catch(error => {
        console.error("Promise rejected:", error);
        return "default value";
      });
    } else {
      return Q.resolve(maybePromise);
    }
  } catch (error) {
    console.error("Synchronous error:", error);
    return Q.reject(error);
  }
}

State Inspection

Methods for examining the current state of promises and extracting their values or reasons.

/**
 * Returns snapshot of promise state
 * @returns Object with state information {state, value?, reason?}
 */
promise.inspect();

/**
 * Tests if promise is waiting for result
 * @returns True if promise is pending
 */
promise.isPending();

/**
 * Tests if promise has fulfillment value
 * @returns True if promise is fulfilled
 */
promise.isFulfilled();

/**
 * Tests if promise has rejection reason
 * @returns True if promise is rejected
 */
promise.isRejected();

Usage Examples:

const Q = require("q");

// Inspect promise states
const pendingPromise = Q.delay("result", 1000);
const fulfilledPromise = Q.resolve("success");
const rejectedPromise = Q.reject(new Error("failure"));

console.log(pendingPromise.inspect());
// { state: "pending" }

console.log(fulfilledPromise.inspect());
// { state: "fulfilled", value: "success" }

console.log(rejectedPromise.inspect());
// { state: "rejected", reason: Error("failure") }

// Use state checking methods
console.log(pendingPromise.isPending());    // true
console.log(fulfilledPromise.isFulfilled()); // true
console.log(rejectedPromise.isRejected());   // true

// Conditional processing based on state
function processPromiseArray(promises) {
  const results = promises.map(promise => {
    const inspection = promise.inspect();
    
    switch (inspection.state) {
      case "fulfilled":
        return { success: true, data: inspection.value };
      case "rejected":
        return { success: false, error: inspection.reason.message };
      case "pending":
        return { success: false, error: "Still pending" };
      default:
        return { success: false, error: "Unknown state" };
    }
  });
  
  return results;
}

// Monitoring promise progress
function monitorPromise(promise, name) {
  const startTime = Date.now();
  
  const checkStatus = () => {
    const elapsed = Date.now() - startTime;
    const inspection = promise.inspect();
    
    console.log(`[${elapsed}ms] ${name}: ${inspection.state}`);
    
    if (inspection.state === "pending") {
      setTimeout(checkStatus, 100); // Check again in 100ms
    } else if (inspection.state === "fulfilled") {
      console.log(`[${elapsed}ms] ${name}: completed with value:`, inspection.value);
    } else {
      console.log(`[${elapsed}ms] ${name}: failed with error:`, inspection.reason.message);
    }
  };
  
  checkStatus();
  return promise;
}

// Usage
const slowOperation = Q.delay("finished", 2000);
monitorPromise(slowOperation, "Slow Operation");

String Representation

Methods for converting promises to string representations for debugging and logging.

/**
 * Returns string representation of promise
 * @returns "[object Promise]"
 */
promise.toString();

Usage Examples:

const Q = require("q");

// String representation
const promise = Q.resolve("test");
console.log(promise.toString()); // "[object Promise]"

// Use in logging
function logPromise(promise, name) {
  console.log(`Promise ${name}: ${promise.toString()}`);
  console.log(`State: ${promise.inspect().state}`);
  
  return promise.then(
    value => {
      console.log(`Promise ${name} fulfilled with:`, value);
      return value;
    },
    error => {
      console.log(`Promise ${name} rejected with:`, error.message);
      throw error;
    }
  );
}

// Debug helper
function debugPromise(promise) {
  const inspection = promise.inspect();
  const stringRep = promise.toString();
  
  return {
    string: stringRep,
    state: inspection.state,
    value: inspection.value,
    reason: inspection.reason,
    isPending: promise.isPending(),
    isFulfilled: promise.isFulfilled(),
    isRejected: promise.isRejected()
  };
}

// Usage
const testPromise = Q.delay("result", 500);
console.log("Debug info:", debugPromise(testPromise));

setTimeout(() => {
  console.log("Debug info after delay:", debugPromise(testPromise));
}, 600);

Advanced State Queries

Advanced methods for examining promise state in complex scenarios.

/**
 * Inspection state object interface
 */
interface InspectionState {
  state: "pending" | "fulfilled" | "rejected";
  value?: any;    // Present when state is "fulfilled"
  reason?: any;   // Present when state is "rejected"
}

Usage Examples:

const Q = require("q");

// Batch state analysis
function analyzePromiseBatch(promises) {
  const analysis = {
    total: promises.length,
    pending: 0,
    fulfilled: 0,
    rejected: 0,
    values: [],
    errors: []
  };
  
  promises.forEach(promise => {
    const inspection = promise.inspect();
    
    switch (inspection.state) {
      case "pending":
        analysis.pending++;
        break;
      case "fulfilled":
        analysis.fulfilled++;
        analysis.values.push(inspection.value);
        break;
      case "rejected":
        analysis.rejected++;
        analysis.errors.push(inspection.reason);
        break;
    }
  });
  
  return analysis;
}

// Promise pool monitoring
class PromisePool {
  constructor() {
    this.promises = new Map();
  }
  
  add(name, promise) {
    this.promises.set(name, promise);
    return promise;
  }
  
  getStatus() {
    const status = {};
    
    this.promises.forEach((promise, name) => {
      const inspection = promise.inspect();
      status[name] = {
        state: inspection.state,
        hasValue: inspection.hasOwnProperty("value"),
        hasReason: inspection.hasOwnProperty("reason")
      };
    });
    
    return status;
  }
  
  getCompleted() {
    const completed = [];
    
    this.promises.forEach((promise, name) => {
      if (!promise.isPending()) {
        completed.push({ name, promise });
      }
    });
    
    return completed;
  }
}

// Usage
const pool = new PromisePool();
pool.add("fast", Q.delay("fast result", 100));
pool.add("slow", Q.delay("slow result", 500));
pool.add("error", Q.reject(new Error("test error")));

setTimeout(() => {
  console.log("Pool status:", pool.getStatus());
  console.log("Completed:", pool.getCompleted().map(c => c.name));
}, 200);

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