util.promisify and util.callbackify
Hard · Async Patterns
Old Node.js APIs use error-first callbacks: the last argument is callback(err, value). util.promisify turns such a function into one that returns a promise, and util.callbackify does the opposite. Implement both, following real Node behaviour.
promisify(original):
- If original is not a function, throw a TypeError with code: "ERR_INVALID_ARG_TYPE".
- If original[promisify.custom] is set, return that function instead (promisify.custom is Symbol.for("nodejs.util.promisify.custom"), already defined in the starter).
- Otherwise return a new function that calls original with the same this and arguments plus a callback, and returns a Promise: reject with err if it is truthy, otherwise resolve with the first value (extra values are ignored).
- The returned function must have [promisify.custom] set to itself, so promisifying it again returns the same function.
callbackify(original) (original returns a promise):
- Return a function whose last argument is the callback. It calls original with the same this and the other arguments.
- On success call callback(null, value). On rejection call callback(reason).
- If the rejection reason is falsy (null, 0, ""...), wrap it: an Error with message "Promise was rejected with falsy value", code: "ERR_FALSY_VALUE_REJECTION" and reason set to the original value.
- The callback always runs asynchronously. (Node uses process.nextTick; here use queueMicrotask.)
The starter contains fake callback APIs and a driver runScenario(name) that exercises your functions and returns a plain summary.