Skip to curriculum
Jump to the editor

12.3. Promisify a callback API

Easy
Topics
10–15 min

Older browser and Node.js APIs report their result through a callback, fn(arg, (error, value) => …). Newer code wants a promise, so it can use await, try/catch and promise combinators. A promisify helper bridges the two: it turns a callback function into one that returns a promise, once, instead of wrapping every call by hand.

Write promisify(fn) in promisify.js.

Signature

JAVASCRIPT
function promisify(fn) // returns a function that returns a Promise
  • fn: a function whose last argument is a callback (error, value).
  • The returned function takes the same arguments as fn, without the callback, and returns a new promise.

Requirements

  1. promisify(fn) returns a function and does not call fn yet.
  2. Each call of that function calls fn with its arguments plus one callback, last, and returns a new promise.
  3. The promise settles when fn calls back: rejected with error when error is truthy, otherwise fulfilled with value. Further values passed to the callback are ignored.
  4. The promise settles only once, even if fn calls back again.
  5. this is passed through: a promisified method still sees its object. It is fn itself that runs, even when fn has its own property named call or apply.
  6. If fn throws during the call, the promise rejects with that error; the call itself does not throw.
  7. promisify throws a TypeError when fn is not a function.

Examples

JAVASCRIPT
function readSetting(name, callback) {
  setTimeout(() => callback(null, name === "theme" ? "dark" : undefined), 100);
}

const readSettingAsync = promisify(readSetting);
const theme = await readSettingAsync("theme"); // "dark", 100 ms later
JAVASCRIPT
const failing = promisify((callback) => callback(new Error("no access")));

try {
  await failing();
} catch (error) {
  console.log(error.message); // "no access"
}
JAVASCRIPT
const counter = {
  count: 3,
  read(callback) { callback(null, this.count); },
};
counter.readAsync = promisify(counter.read);
await counter.readAsync(); // 3: this is counter

Environment

  • Plain JavaScript in a browser page; the tests call the global promisify from promisify.js.
  • The tests use a virtual clock for setTimeout, so no test waits for real time.
  • Callbacks with several values and custom promise versions are problem 12.4.

Hints

  1. Where can you call fn so that both resolve and reject are in reach from its callback?
  2. Which kind of function receives the caller's this: an arrow function or a regular one?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…