by ascagnel_ · 9y ago · 0 comments
function fetchFirstUser(isWhatIWant, callback) {
knex.first().from('users')
.then(user => ({ user }))
.catch(e => ({ e }))
.then(({ user, e }) => {
if (user) {
callback(user);
} else {
callback(e);
}
});
}
By only calling your callback function after a catch statement, you guarantee that (a) an exception generated by the callback will not be swallowed by the catch statement and that (b) the callback is called exactly once in the promise chain.For golfing purposes, you can remove a branch too:
function fetchFirstUser(isWhatIWant, callback) {
knex.first().from('users')
.then((user) => ({ user }), (e) => ({ e }))
.then(({ user, e }) => callback(e, user))
.catch((e) => console.error(e));
}