Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Write a promisify function in JavaScript

20 Write promisify, and find the this it loses

fair

Write a general promisify(fn) for error-first callback functions. Then promisify a method and find out why it fails, and what fixes it.

Stuck? Three hints, smallest first
  1. 1. Collect the caller’s arguments with a rest parameter and append your own callback.
  2. 2. The wrapper calls fn(...) as a plain function, so this inside it is not the object it came from.
  3. 3. fn.bind(obj) before promisifying, or pass the receiver in.

The answer

const promisify = (fn) => (...args) =>
  new Promise((resolve, reject) => {
    fn(...args, (err, value) => (err ? reject(err) : resolve(value)));
  });

const readFee = (plate, callback) => {
  const fees = { 'LAG-441-XA': 2500, 'ABJ-772-KM': 4000 };
  Promise.resolve().then(() =>
    plate in fees ? callback(null, fees[plate]) : callback(new Error('unknown plate: ' + plate))
  );
};

const feeFor = promisify(readFee);

// A METHOD is the problem case: it needs its receiver.
const till = {
  total: 9000,
  read(callback) { callback(null, this.total); },
};
const detachedFails = (() => {
  try { const loose = till.read; loose(() => {}); return 'no throw'; }
  catch (e) { return e.constructor.name; }
})();
const readTotal = promisify(till.read.bind(till));

console.log('fee      :', await feeFor('LAG-441-XA'));
console.log('unknown  :', await feeFor('XXX').then(() => 'resolved', (e) => e.message));
console.log('detached method:', detachedFails);
console.log('bound then promisified:', await readTotal());

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a promisified function resolves with the callback value', await feeFor('LAG-441-XA'), 2500);
test('and rejects with the callback error', await feeFor('XXX').then(() => 'resolved', (e) => e.message), 'unknown plate: XXX');
test('a detached method loses this, so promisify alone is not enough', detachedFails, 'TypeError');
test('binding the receiver first fixes it', await readTotal(), 9000);
test('the wrapper reports arity 0, because of the rest parameter', feeFor.length, 0);
test('extra callback arguments beyond the first value are dropped', await promisify((cb) => cb(null, 1, 2))(), 1);
test('a falsy error still counts as success', await promisify((cb) => cb(undefined, 'fine'))(), 'fine');
test('but a callback that reports 0 as its error would reject nothing', await promisify((cb) => cb(0, 'suspicious'))(), 'suspicious');

The rest-and-append trick is the whole of promisify: take whatever the caller passed, put your callback last, and let the promise constructor do the rest. Node's util.promisify is this plus a symbol so a library can supply its own custom version.

The this failure is the one that catches people, and it is not really about promisify at all — const loose = till.read; loose(cb) fails the same way. Extracting a method from an object severs it from its receiver, and in strict mode this is undefined rather than the global object, so this.total throws instead of quietly reading nothing. Exercise 72 is this trap on its own.

The last two assertions are the contract's soft spot. "Error-first" is a convention enforced by nothing, so a truthy check is all promisify can do. A callback that hands back 0 or ‘’ as its error is treated as success, and one that hands back several values loses everything after the first. Both are why promisify is a bridge to be crossed once, at the edge of the codebase, and not a pattern to build on.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.