Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
12.3. Promisify a callback API
Easy
Topics
This question is in
12. Callbacks, promises and asyncOlder browser and Node.js APIs report their result through a callback, fn(arg, (error, value) => …). Newer code wants a promise, so it can use await, try/catch and promise combinators. A promisify helper bridges the two: it turns a callback function into one that returns a promise, once, instead of wrapping every call by hand.
Write promisify(fn) in promisify.js.
Signature
function promisify(fn) // returns a function that returns a Promisefn: a function whose last argument is a callback(error, value).- The returned function takes the same arguments as
fn, without the callback, and returns a new promise.
Requirements
promisify(fn)returns a function and does not callfnyet.- Each call of that function calls
fnwith its arguments plus one callback, last, and returns a new promise. - The promise settles when
fncalls back: rejected witherrorwhenerroris truthy, otherwise fulfilled withvalue. Further values passed to the callback are ignored. - The promise settles only once, even if
fncalls back again. thisis passed through: a promisified method still sees its object. It isfnitself that runs, even whenfnhas its own property namedcallorapply.- If
fnthrows during the call, the promise rejects with that error; the call itself does not throw. promisifythrows aTypeErrorwhenfnis not a function.
Examples
function readSetting(name, callback) {
setTimeout(() => callback(null, name === "theme" ? "dark" : undefined), 100);
}
const readSettingAsync = promisify(readSetting);
const theme = await readSettingAsync("theme"); // "dark", 100 ms laterconst failing = promisify((callback) => callback(new Error("no access")));
try {
await failing();
} catch (error) {
console.log(error.message); // "no access"
}const counter = {
count: 3,
read(callback) { callback(null, this.count); },
};
counter.readAsync = promisify(counter.read);
await counter.readAsync(); // 3: this is counterEnvironment
- Plain JavaScript in a browser page; the tests call the global
promisifyfrompromisify.js. - The tests use a virtual clock for
setTimeout, so no test waits for real time. - Callbacks with several values and custom promise versions are problem 12.4.
Hints
- Where can you call
fnso that bothresolveandrejectare in reach from its callback? - Which kind of function receives the caller's
this: an arrow function or a regular one?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…