Write promisify(fn): turn a Node-style callback function into one that returns a promise.
fn is written in the Node.js callback style: it takes its arguments followed by a callback, and when it's done it calls callback(error, result), with error set to null when it worked.
promisify(fn) returns a new function that takes the same arguments without the callback and returns a promise. The promise rejects with error when there is one, and otherwise fulfills with result.
Keep this, so methods can be promisified.
function promisify(fn) {
// your code
}
// function add(a, b, callback) {
// setTimeout(() => callback(null, a + b), 100);
// }
// const addAsync = promisify(add);
// await addAsync(2, 3); // 5
// await promisify((callback) => callback(new Error("offline")))(); // rejects with Error "offline"
// const counter = { n: 7, read(callback) { callback(null, this.n); } };
// counter.readAsync = promisify(counter.read);
// await counter.readAsync(); // 7: this is still counter
Solve it in the editor, with tests
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…