deferential: Promise/Callback Dual API Helper

1.0.0 · maintenance · verified Tue Apr 21

deferential is a lightweight JavaScript utility designed to assist in building APIs that support both Node.js-style callbacks and native ES6 Promises. It provides a `Deferred` object, which acts as an intermediate for managing the resolution or rejection of a promise, and a `nodeify` method to conditionally return a promise or invoke a callback. The package is at version 1.0.0, indicating a stable but likely infrequent release cadence given its focused scope and the maturity of native Promise implementations. Its key differentiator lies in offering a minimalistic approach to deferred patterns, avoiding the heavier overhead of full-fledged promise libraries like Q or Bluebird by leveraging native browser/Node.js ES6 Promises. It's particularly useful for adapting existing callback-based code to also expose a promise-based interface without rewriting the core logic.

Common errors

Warnings

Install

Imports

Quickstart

This code demonstrates how to create a function (`getFile`) that can be consumed with both Node.js-style callbacks and native ES6 Promises using `deferential`.

const Promise = require('native-promise-only'); // Polyfill for older environments
const fs = require('fs');
const Deferred = require('deferential');

function getFile(fileName, cb) {
  const d = Deferred();
  fs.readFile(fileName, 'utf8', d.resolver());
  return d.nodeify(cb);
}

// Example usage with callback
getFile('myfile.text', function (err, data) {
  if (err) return console.error('Callback error:', err.message);
  console.log('Callback data:', data.substring(0, 50) + '...');
});

// Example usage with Promise
getFile('myfile.txt')
  .then(function (data) {
    console.log('Promise data:', data.substring(0, 50) + '...');
  })
  .catch(function (err) {
    console.error('Promise error:', err.message);
  });

// To make the example runnable, create a dummy file
fs.writeFileSync('myfile.text', 'This is some dummy content for the deferential example file. It demonstrates how the package can handle both callback-based and promise-based APIs simultaneously. This makes it easier to migrate or support legacy code while offering modern promise interfaces.');
fs.writeFileSync('myfile.txt', 'This is some dummy content for the deferential example file. It demonstrates how the package can handle both callback-based and promise-based APIs simultaneously. This makes it easier to migrate or support legacy code while offering modern promise interfaces.');

view raw JSON →