#Promises#Async

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

By Pratik RaiMedium

Write promisify(fn), where fn takes any number of arguments followed by a callback called as callback(error, value).

Return a new function that takes the same arguments without the callback and returns a promise: it rejects with error when that argument is truthy, and resolves with value otherwise.

Examples

Input:

JSfile.javascript
1const readValue = (key, cb) => 2 key ? cb(null, 'value for ' + key) : cb(new Error('key required')); 3 4await promisify(readValue)('a');

Output:

"value for a"

The callback reported no error, so the promise resolves with the second argument.

Constraints

  • fn always calls its callback exactly once

Notes

  • This is what util.promisify does in Node, and what wrapping an old browser API looks like.

How to solve it

Bridging two eras

Callback APIs pass (error, value) by convention: a truthy first argument means failure. Promisifying is mechanical once you see that the convention maps exactly onto reject and resolve.

Approach

Collect the caller's arguments with a rest parameter, append your own callback, and translate.

Implementation

JSfile.javascript
1function promisify(fn) { 2 return function (...args) { 3 return new Promise((resolve, reject) => { 4 fn.call(this, ...args, (error, value) => { 5 if (error) reject(error); 6 else resolve(value); 7 }); 8 }); 9 }; 10}

Worth knowing

The returned function creates the promise inside itself, not around itself, so nothing runs until it is called.

Node ships this as util.promisify, and it is what wrapping an older browser API looks like. The real-world wrinkle is a callback that fires more than once: a promise ignores every settle after the first, which is usually what you want but hides the bug.

Goal: Return a function that produces a promise, resolving or rejecting on the callback convention.

Frequently asked questions

What does it mean to promisify a function?
To wrap a callback-based function so it returns a promise instead. The wrapper supplies its own callback, then resolves or rejects depending on what that callback receives.
What is the (error, value) callback convention?
Node's convention that a callback's first argument is an error and the second is the result, so a successful call passes null first. It exists because callbacks have no equivalent of a catch block.
Does Node provide this already?
Yes — util.promisify does exactly this, and most Node APIs now ship promise versions directly. Implementing it by hand is asked because it shows you understand what a promise wraps.
What if the callback fires more than once?
A promise settles once and ignores every later call, so the extra invocations vanish silently. That is usually the behaviour you want, but it can hide a genuine bug in the callback API.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Pool With a Concurrency Limit

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Time Out an Async Function

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Resolve Promises Sequentially

Run promises one after another and collect the results in order — built with .then chaining, no async/await.

JavaScript · ES6 — Pratik Rai ·