4 ms·
If you must call the callback, you could simplify this pattern as such: function fetchFirstUser(isWhatIWant, callback) { knex.first().from('users')
by ascagnel_ 10y ago
If you must call the callback, you could simplify this pattern as such:
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.
- Vevolut 10y agoI may be mistaken but I don't think this will work exactly how you expect it to. If theres an unhandled exception thrown somewhere in the callback then it will fail silently. You need to add a .catch(console.error.bind(console)); at the very end to get back to default behavior.
- spankalee 10y agoI like this! 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)); }