We've got a number of libraries that currently support callbacks that we're updating to support Promises. There are two approaches I'm looking at.
- Default to cb behavior and do something special if a Promise is needed
const cbAndPromiseOption1 = cb => {
if(!cb){
return new Promise((resolve, reject) => {
cbAndPromiseOption1((err, data) => {
try {
err ? reject(err) : resolve(data);
} catch (uncaughtErr) {
/*handle uncaught error from reject / resolve*/
}
})
})
}
let err;
let data;
//...do stuff
cb(err, data);
}
- Default to Promise behavior and do something special if cb is provided
const cbAndPromiseOption2 = cb => {
let promiseToReturn = new Promise((resolve, reject) => {
let err;
let data;
//...do stuff
err ? reject(err) : resolve(data);
});
if(cb){
promiseToReturn = promiseToReturn.then(data => cb(null, data)).catch(err => cb(err)).catch(uncaughtErr => {/*handle uncaught error from cb to avoid unhandled promise errors*/});
}
return promiseToReturn;
}
My question is whether these are functionally equivalent or if there's some obvious difference I'm overlooking. Option 1 is the approach I've seen in numerous places, but Option 2 is more appealing to me because it gets the dev in the mindset of Promise-first behavior.
In any case, any feedback on which of these approaches is "better" would be very much appreciated.