#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.

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

Source

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

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 · ES6Pratik Rai ·

JavaScript

Promise Time Limit

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

JavaScript · ES6Pratik Rai ·

JavaScript

Resolve Promises Sequentially

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

JavaScript · ES6Pratik Rai ·