`throw` as an expression?
probably not exactly the fat arrow usage you were looking for ... but it makes it trivial to inline any sort of block
asyncFunc()
.then(count => count >= 0 ? count : ()=>{throw new Error(...)}())
.then(...)
.catch(...);
or a simple utility method
John Lenz wrote:
or a simple utility method
Current keyword-anchored statement form does not require parens around expression to evaluate and throw.
It would be convenient for throw to be one. Maybe an idea would be to
treat it similar to void
or delete
? If it were an expression, it
could be parsed very similarly. Here's a potential use case even
without all the other ES6 additions.
function foo(bar) {
bar == null && throw new TypeError();
// do stuff with required parameter `bar`
}
// Currently, it requires this:
function foo(bar) {
if (bar == null) {
throw new TypeError();
}
// do stuff with required parameter `bar`
}
// Or, this: (totally stealing your hack, Andrea... :-P)
const foo = bar => bar == null ?
()=>{throw new TypeError()} :
undefined; /* do something */
It wouldn't surprise me if this becomes included eventually in, say,
Underscore/Lodash/etc. if not made an expression. It would just end up
easier to type _.throw(new TypeError())
.
To clarify, here's what I mean by treating it like void
and delete
:
void foo(); //=> returns undefined
delete bar[0]; //=> returns if the entry/property no longer exists
throw baz; //=> returns nothing/undefined (for sake of spec)?
Sure, but there is no pressing need here, "return" as an expression would be more interesting. Not that I'm asking for that.
Use case: With promises, the expression body form of arrow functions is so convenient. Alas,
throw
being a statement, you can’t use it there. For example, the following code is not syntactically legal:asyncFunc() .then(count => count >= 0 ? count : throw new Error(...)) .then(...) .catch(...);
Could
throw
be turned into an expression?