FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Promisify II

30mins

Create a function promisify(fn) that converts a Node.js-style callback function into a function that returns a promise.

The difference from the standard version is:

  • If the original function explicitly returns a value, that return value should be used instead of the promise.
  • If the function returns undefined, then the promise-based behavior should take place.
  • The callback signature is (err, result).

Examples

function asyncAdd(a, b, cb) { setTimeout(() => cb(null, a + b), 100); } const promisedAdd = promisify(asyncAdd); promisedAdd(2, 3).then(console.log); // 5 function syncReturn(x) { return x * 2; } const wrapped = promisify(syncReturn); console.log(wrapped(4)); // 8, returns directly instead of a Promise

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests