by hiphipjorge · 10y ago · 0 comments
export default function getUsers () {
return new Promise((resolve, reject) => {
getUsers().then(users => {
filterUsersWithFriends(users)
.then(resolve)
.catch((err) => {
resolve(trySomethingElse(users));
});
}, reject)
});
}
There is never a need to write this type of terrible code if you're using promises. The solution this is not async/await. I agree that async/await and generators are nice, but saying they solve a problem that is not actually a problem seems a little silly.This is typical of many technical blog posts: Overcomplicate a solution that could be done much more cleanly and clearly in order to show off a new feature, when in reality that feature is actually not that useful.
export default function getUsers () {
return getUsers().then(users => {
return filterUsersWithFriends(users)
.catch(err => trySomethingElse(users));
});
}
Or if you like one-liners: export default function getUsers () {
return getUsers().then(users => filterUsersWithFriends(users).catch(err => trySomethingElse(users)));
} export default function getUsers () {
return getUsers()
.then(users => filterUsersWithFriends)
.then(getUsersLikes, trySomethingElse);
}
would have been more than enough. task getUsersWithFriends() {
users <- getUsers();
catch (e) {
return trySomethingElse(users);
}
// Everything below is protected by the catch above.
withFriends <- filterUsersWithFriends(users);
return withFriends;
}
.. with errors propagating to nodejs style callbacks automatically. No need for overheads like "promisifyAll" either. cspjs turns the task into a state machine. Better semantics for catch and finally where you can retry operation from within catch clause (ex: exponential backoff).disclosure: author of cspjs. couldn't help shameless plug since this was being touted as the "future" in the original post!
await getUsers(), defer err, users
return cb err if err?
await filterUsersWithFriends users, defer err, users
return cb err, users
I seriously don't get how people like Javascript when to do such a simple things you need so much code that looks so ugly (IMO).And to make the error handling even cleaner, check out the errify/errorCallback pattern:
http://maxtaco.github.io/programming/2014/09/18/handling-err...
https://www.npmjs.com/package/errify
https://github.com/nextorigin/express-rendertype/blob/master...
defer = require 'defer-esc'
await req.get 'https://x.io', defer err, http, res # if err will call cb err
await req.get "https://x.io?hash=#{res.hash}", defer err, http, res # if err will call cb err
return cb res