A comprehensive promise library implementing CommonJS Promises/A,B,D specifications for JavaScript
npx @tessl/cli install tessl/npm-q@2.0.0Q is a comprehensive promise library for JavaScript that implements the CommonJS Promises/A, B, and D specifications. It provides a robust foundation for asynchronous programming with features including promise chaining, error propagation, progress notifications, and utilities for combining multiple promises. Q supports both Node.js and browser environments, provides long stack trace support for debugging, and includes adapter functions for converting Node.js callback-style functions to promise-based ones.
npm install qconst Q = require("q");ESM (if using transpiler):
import Q from "q";For specific functions (all are properties of Q):
const Q = require("q");
const { defer, delay, all, race } = Q;const Q = require("q");
// Create a promise from a value
const promise = Q("Hello World");
// Create a deferred
const deferred = Q.defer();
setTimeout(() => {
deferred.resolve("Delayed result");
}, 1000);
// Chain promises
promise
.then(value => value.toUpperCase())
.then(value => console.log(value))
.catch(error => console.error(error))
.done();
// Convert Node.js callback to promise
const fs = require("fs");
const readFile = Q.denodeify(fs.readFile);
readFile("package.json", "utf8")
.then(data => JSON.parse(data))
.then(json => console.log(json.name))
.catch(console.error);Q is built around several key components:
Essential functions for creating and managing promises from values, errors, and callback functions.
// Main promise creation function
function Q(value);
// Create deferred objects
function Q.defer();
// Create rejected promises
function Q.reject(error);
// Promise constructor
function Q.Promise(resolver);
// Try function execution
function Q.try(callback);Methods for examining promise state and extracting information about promise fulfillment status.
// Test promise type
function Q.isPromise(object);
// Instance state inspection methods
promise.inspect();
promise.isPending();
promise.isFulfilled();
promise.isRejected();Functions for working with arrays of promises, combining multiple asynchronous operations.
// Process arrays of promises
function Q.all(promises);
function Q.allSettled(promises);
function Q.spread(promise, fulfilled, rejected);
function Q.race(promises);
// Instance collection methods
promise.all();
promise.allSettled();
promise.spread(fulfilled, rejected);Utilities for controlling promise execution timing, delays, timeouts, and conditional processing.
// Timing control
function Q.delay(object, timeout);
function Q.timeout(object, ms, message);
function Q.when(value, fulfilled, rejected, ms);
// Instance timing methods
promise.delay(ms);
promise.timeout(ms, message);
promise.finally(callback, ms);Function wrappers and utilities for integrating promises with functional programming patterns.
// Function wrapping
function Q.function(wrapped);
function Q.promised(callback);
function Q.join(x, y);
// Async/generator support
function Q.async(makeGenerator);
function Q.spawn(makeGenerator);Comprehensive Node.js callback integration for converting existing callback-based APIs to promises.
// Node.js callback conversion
function Q.denodeify(callback, pattern);
function Q.ninvoke(object, name, ...args);
// Instance Node.js methods
promise.ninvoke(name, ...args);
promise.nodeify(nodeback);Core promise instance methods for building promise chains with transformations and error handling.
// Chain building
promise.then(fulfilled, rejected, ms);
promise.catch(rejected);
promise.done(fulfilled, rejected);
promise.finally(callback, ms);
// Value transformation
promise.thenResolve(value);
promise.thenReject(error);Methods for accessing properties and calling methods on promised values.
// Property access
promise.get(name);
promise.keys();
// Method calling
promise.invoke(name, ...args);
promise.apply(thisp, args);
promise.call(thisp, ...args);
promise.bind(thisp, ...args);Advanced features including low-level dispatch, pass-by-copy semantics, and timing estimates.
// Low-level operations
promise.dispatch(op, args);
promise.rawDispatch(resolve, op, args);
// Pass-by-copy
function Q.passByCopy(value);
function Q.isPortable(value);
promise.pass();
promise.toBePassed();
// Timing estimates
promise.observeEstimate(emit);
promise.getEstimate();FIFO queue implementation using promises for producer-consumer patterns.
// Queue constructor and methods (from queue.js module)
function Queue();
queue.put(value);
queue.get();// Core interfaces
interface Deferred {
promise: Promise;
resolve(value): void;
reject(reason): void;
setEstimate(estimate): void;
makeNodeResolver(unpack?): Function;
}
interface PromiseState {
state: "pending" | "fulfilled" | "rejected";
value?: any;
reason?: any;
}
// Configuration
interface QConfiguration {
longStackSupport: boolean;
onerror: Function;
isIntrospective: boolean;
}Q provides comprehensive error handling with long stack traces and global error handlers:
// Enable long stack traces
Q.longStackSupport = true;
// Set global error handler
Q.onerror = function(error) {
console.error("Unhandled promise rejection:", error);
};
// Disable stack trace filtering for debugging
Q.isIntrospective = true;
// Promise-specific error handling
promise
.catch(error => {
// Handle specific errors
if (error instanceof TypeError) {
return "Default value";
}
throw error; // Re-throw unhandled errors
})
.done(); // Ensure uncaught errors are thrown