41Implement promisify() for callback-based APIs
mediumAbout 35 minutesCodingpromisescallbacksnode
Problem
Many older APIs take a Node-style callback as their last argument: callback(error, result). Implement promisify(fn), which returns a function that takes the same arguments without the callback and returns a promise instead.
function readConfig(name, callback) {
setTimeout(() => {
if (!name) callback(new Error("Missing name"));
else callback(null, { name, theme: "light" });
}, 10);
}
const readConfigAsync = promisify(readConfig);
const config = await readConfigAsync("app"); // { name: "app", theme: "light" }Requirements
- Reject when the callback's first argument is truthy; resolve with the second argument otherwise.
- Keep
this, so promisified methods still work:obj.load = promisify(obj.load). - If
fnthrows synchronously, reject instead of throwing. - If the callback is called more than once, only the first call counts.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
The returned function must be a function, not an arrow function, so it can pass its own this on to fn.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.