Promisify a Callback Function

PromisesAsyncHigher-Order Functions

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

Example 1
Input
const readValue = (key, cb) =>
  key ? cb(null, 'value for ' + key) : cb(new Error('key required'));

await promisify(readValue)('a');
Output
"value for a"
Explanation
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.

Hints

Read the full write-up for Promisify a Callback Function
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it