JavaScript · Promises · Senior · Best Practice
What is a thenable, and how would you safely promisify a callback API?
Short Interview Answer
A thenable is any object with a `.then` method; Promise resolution assimilates thenables. Promisify with `new Promise` and forward err/result exactly once.
Detailed Explanation
The Promises/A+ assimilation rule means returning/resolving a thenable links states — useful and sometimes surprising if a non-promise object accidentally has `then`. To promisify: `new Promise((resolve, reject) => api(arg, (err, data) => err ? reject(err) : resolve(data)))`. Guard against double callbacks. Prefer Node `util.promisify` when available. Do not wrap an existing promise in another unnecessary `new Promise` (promise constructor anti-pattern).
Example
function readFileP(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => (err ? reject(err) : resolve(data)));
});
}Interview Tip
Call out the promise constructor anti-pattern.
Common Mistake
Wrapping already-async promise-returning functions in `new Promise`.