assertchris / attempt-promise Goto Github PK
View Code? Open in Web Editor NEWAlternative to try-catch wrapping async/await
License: MIT License
Alternative to try-catch wrapping async/await
License: MIT License
I like your way of thinking with this quite a lot (it's also nice to see some "multiple returns" with array destruction in the wild!)
but I do feel like, and please correct me if I'm wrong that the try-catch problem could be solved with vanilla JS.
This is because, and again please correct me if wrong, a promise is like a try block in and of itself, with optional catch blocks in the form of a call to the catch
method or a second callback for then
to illustrate I take your example and transform it to vanilla JS
const id = session.get("id");
const [err1, user] = await attempt(User.find(id));
if (err1) {
response.error("Oops! No user...");
return;
}
const [err2, products] = await attempt(
Product.where("user_id", user.id)
.orderBy("updated_at", "desc")
.limit(50)
.fetch(),
);
if (err2) {
response.error("Oops! Missing products...");
return;
}
response.ok("here are your products...", products);
vanilla:
const id = session.get("id");
return User.find(id)
.catch(e => response.error("Oops! No user..."))
.then(user => Product.where("user_id", user.id).orderBy("updated_at", "desc").limit(50).fetch())
.catch(e => response.error("Oops! Missing products..."))
.then(products = > response.ok("here are your products...", products));
(I would like to note that I have some doubts about the vanilla one regarding the catch
calls, in my expierence, but its been a while, the catch
does not break the chain. However the information I just looked up(https://stackoverflow.com/a/20715224) suggest it does, so I wrote the code based on what I found);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.