FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Promisify

15mins

Before Promises/async–await were common, many JS APIs used a callback-last, error-first style: (…args, callback), where callback has the signature (err, value).

Implement promisify(fn) which:

  • Accepts a function fn that expects its final argument to be (err, value) => void.
  • Returns a new function that returns a Promise instead of requiring a callback.
  • On success (callback called with null or undefined error), the Promise resolves with the value.
  • On failure (callback called with an error), the Promise rejects with that error.
  • It should preserve this context when the returned function is called (i.e., use fn.call(this,…)).
  • If fn throws synchronously, the Promise should reject with that error.

Example

// Callback-last, error-first function function foo(url, options, callback) { fakeRequest(url, options) .then((data) => callback(null, data)) .catch((err) => callback(err)); } const promisifiedFoo = promisify(foo); // Now usable with async/await: const data = await promisifiedFoo("example.com", { q: 1 });

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests