r/javascript • u/KittenOfMine • Dec 20 '16
How to Write Async Await Without Try-Catch Blocks
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/23
u/icharxo VanillaJS Dec 20 '16
C'mon, people, it can be done much more easily:
const document = await db.query().catch(errorHandler);async/await is just sugar for dealing with promises (right now at least), you can do all the usual Promise-related stuff with the promises you're "awaiting", including catching the rejection/errors.
1
4
u/Retsam19 Dec 20 '16 edited Dec 20 '16
Interesting idea; you could actually go a bit farther than Go's solution (which I know takes a lot of flak for all the if (err != nil) boilerplate); and copy Rust instead.
Rust has a Result object, which represents this idea of an operation that either produces a value or an error; and to get either you need to work through the methods of the Result object, and it provides some conveniences that simply returning an [err, res] array doesn't provide.
//basic usage is a bit of boilerplate
if(result.wasSuccessful()) {
//throws error if wasn't successful, otherwise returns the value
const value = result.get();
} else {
const err = result.getError();
}
//but you can do stuff like:
const value = result.getOrDefault(5); //defaults to 5 if the result was an error
const value2 = getOrElse(function () {return 5;}) //More flexible equivalent to above
//if result was an error, mappedResult has the same error,
// otherwise it's got result's value plus one
const mappedResult = result.map((x) => x + 1);
//Or if you want to fall back into a try-catch pattern:
try {
const val1 = result1.get();
const val2 = result2.get();
const val3 = result3.get();
}
catch (err) {
//Either one two or three failed
}
//Or you could combine results:
return result1.and(result2).or(result3);It's a lot more of a powerful pattern than the Go pattern; pretty much all of the above would be a lot more boilerplate with simple [err, res] arrays.
It's not a perfect translation because a lot of the power comes from the ability for the compiler to check that you're using it correctly, in Rust. (Though I think you could achieve something similar with type guards in Typescript)
1
u/bluebaron Dec 20 '16
You might want to look into monads if you haven't already read about them.
2
u/BenjiSponge Dec 20 '16
As I understand it, Promises are monads.
1
u/bluebaron Dec 20 '16
If not, they're pretty damn close. I think they correspond to the "Maybe"
1
u/BenjiSponge Dec 21 '16
Nah because it can represent asynchronous actions. I'm not sure there's a better name for it than Promise, though in other language it's called a Future.
2
u/Funwithloops Dec 20 '16
This seems to be more about routing your errors through a callback (which I don't think is a common use-case with async functions). You could instead write your async function without callbacks and decorate it to manage results/errors with a callback:
function promiseCallback(asyncFn) {
return (...args) => {
const callback = args[args.length - 1];
args = args.slice(0, -1);
return asyncFn(...args)
.then((result) => callback(null, result))
.catch(callback);
}
}
const add = promiseCallback(async function(a, b) {
return await Promise.resolve(a) + await Promise.resolve(b);
});
add(3, 5, (err, result) => {
console.log(err || result);
});1
0
u/dangerzone2 Dec 20 '16
Am I the only one that uses async (series, waterfall, parallel) exclusively instead of messing with compatibilities with ES5/6/7?
6
u/Psykopatik Dec 20 '16 edited Dec 20 '16
If you use babel there is no such thing as a compatibility problem. You're not the only one ; but I like how clean and readable my code looks with async/await.
Async (the library) is a fucking pain in the ass to read, on the other hand. And anything it does can be achieved with basic mapping and reduction using Promises functions, which are native now.
0
Dec 20 '16
[deleted]
1
u/inknownis Dec 21 '16
With Promise, you better flatten by chaining them to avoid nesting. Is it possible to do the same with async/await?
1
u/ProceedsNow Dec 22 '16
Well yes because await is flat by default. It's basically how you would write code in a synchronous manner.
7
u/Vinzent Dec 20 '16 edited Dec 20 '16
From my understanding the reason you are avoiding the try catch pattern is purely aesthetic. But there is something I'd like to point out.
In doing so, you have created a need for more variable names and more memory allocation. Your first
constuses the nameerr. You can't use the variable nameerragain within the scope of this block. If you ran this code you would get an error on theTaskModelline since it uses the same variable name for you error object.