[!NOTE] Historical Library: Q was a foundational Promises/A+ implementation before native ES2015 Promises and
async/awaitwere standardized in JavaScript engines.
Q is a promise library designed for Node.js and browsers.
Creating Promises
const Q = require('q');
function asyncAction() {
const deferred = Q.defer();
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) deferred.reject(err);
else deferred.resolve(data);
});
return deferred.promise;
}
Converting Nodebacks (Node.js Callbacks)
Q provides utilities to convert standard Node callback signatures (err, result) into promises:
const fs = require('fs');
// Q.nfcall: Node Function Call
Q.nfcall(fs.readFile, 'file.txt', 'utf-8')
.then((data) => console.log(data))
.catch((err) => console.error(err));
// Q.denodeify: Wrap callback function into promise-returning function
const readFile = Q.denodeify(fs.readFile);
readFile('file.txt', 'utf-8').then(console.log);
Array Combinators
// Q.all: Waits for all to resolve
Q.all([stepA(), stepB()])
.then(([resA, resB]) => {
console.log(resA, resB);
});
// Q.allSettled: Waits for all to finish regardless of success
Q.allSettled([stepA(), stepB()])
.then((results) => {
results.forEach((r) => {
if (r.state === 'fulfilled') console.log(r.value);
else console.error(r.reason);
});
});