Implement promisify with support for a promisify.custom override
A legacy payments SDK exposes every method in callback style: the last argument is a callback called as callback(error, ...values). You are writing the adapter that turns these methods into promise-returning functions. Some SDK methods already know how to return a promise (or need a special adapter), so they can tell promisify to use their own version instead of the generic wrapper.
Implement promisify(fn) and the promisify.custom symbol.
promisify(fn) // => a function that returns a Promise
promisify.custom // => Symbol.for('promisify.custom')
fn with the same arguments and the same this, plus one extra argument: a callback. It returns a new Promise on every call. fn is not called until the wrapper is.error, the promise rejects with it.null, undefined, or any falsy error), the promise resolves:
undefined if no values follow the error;fn throws before calling back, the promise rejects with the thrown value. The wrapper itself never throws.promisify.custom is the symbol Symbol.for('promisify.custom'). Because it comes from the global symbol registry, an SDK can tag its methods without importing your code.fn[promisify.custom] is a function, promisify(fn) returns that function itself, unwrapped.fn[promisify.custom] holds any other value except undefined (for example null or a string), throw a TypeError.[promisify.custom] set to itself, so promisify(promisify(fn)) returns the same wrapper.promisify throws a TypeError if fn is not a function.const sdk = {
currency: 'EUR',
charge(cents, callback) {
setTimeout(() => callback(null, `${cents / 100} ${this.currency}`), 10);
},
refund(id, callback) {
callback(new Error(`refund ${id} failed`));
},
rates(callback) {
callback(null, 1.08, 0.86);
},
};
sdk.chargeAsync = promisify(sdk.charge);
await sdk.chargeAsync(1250); // => '12.5 EUR' (this is sdk)
await promisify(sdk.refund).call(sdk, 'r_9'); // rejects with Error('refund r_9 failed')
await promisify(sdk.rates)(); // => [1.08, 0.86]
function lookup(id, callback) { /* ... */ }
lookup[Symbol.for('promisify.custom')] = (id) => fetchCustomer(id);
promisify(lookup) === lookup[promisify.custom]; // => true
const wrapped = promisify(sdk.rates);
promisify(wrapped) === wrapped; // => true