12.4. Promisify with several results and a custom marker
Topics
This question is in
12. Callbacks, promises and asyncA plain promisify turns (error, value) callbacks into promises, but real callback APIs are not all that simple. Some pass several values: a command runner calls back with (error, stdout, stderr), and a DNS lookup with (error, address, family). A promise has only one value, so those must be packed into one object. And some functions already have a better promise version written by hand, which promisify should hand out instead of building a wrapper. Node.js handles that with a shared marker, the symbol Symbol.for("nodejs.util.promisify.custom"): a function stores its own promise version under it.
Write promisify(fn, names) in promisify.js. The file already sets promisify.custom to that symbol.
Signature
function promisify(fn, names) // returns a function that returns a Promise
promisify.custom // Symbol.for("nodejs.util.promisify.custom")fn: a function whose last argument is a callback(error, ...values).names: optional array of strings, one name per callback value.- An error is a truthy first argument.
Requirements
- Without
names, the returned function's promise fulfills with the callback's first value. - With
names, it fulfills with a new object that has one key per name:names[i]holds thei-th value after the error. Each name is an own data field,"__proto__"included. A name with no value holdsundefined; values beyond the names are dropped. - A truthy error rejects the promise, with or without
names. - If
fn[promisify.custom]is a function,promisifyreturns that function itself (not a wrapper), even whennamesare given. If it holds any other truthy value,promisifythrows aTypeError. - The function
promisifyreturns haspromisify.customset to itself, as a non-enumerable property. So promisifying it again returns the same function. - As in a plain promisify: arguments and
thisare passed tofnitself (even when it has its owncallorapplyproperty) with the callback last, a throw insidefnbecomes a rejection, a second callback changes nothing, and a non-functionfnthrows aTypeError.
Examples
function run(command, callback) {
setTimeout(() => callback(null, "built in 2s", "1 warning"), 100);
}
const runAsync = promisify(run, ["stdout", "stderr"]);
await runAsync("build"); // { stdout: "built in 2s", stderr: "1 warning" }function lookup(host, callback) { callback(null, "203.0.113.7"); }
await promisify(lookup, ["address", "family"])("example.test");
// { address: "203.0.113.7", family: undefined }function sleep(ms, callback) { setTimeout(callback, ms); }
sleep[promisify.custom] = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
promisify(sleep) === sleep[promisify.custom]; // true: the hand-written versionconst once = promisify(run);
promisify(once) === once; // trueEnvironment
- 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. - Copying
fn's other properties or prototype onto the new function is out of scope.
Hints
- How do you collect every callback value after the error, however many there are?
- What can
promisifycheck first, before it builds anything, to return an existing promise version? - If the new function stored itself under the marker, what would a second
promisifycall find?
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