Reputation: 1471
How can I write this simple callback with arrow function?
(error) => {
throw error
}
The following doesn't work:
(error) => throw error
Upvotes: 0
Views: 1367
Reputation: 2251
If you don't use a block like {} as body of an arrow function , the body must be an expression. Like if you use
(error) => throw error
is equivalent to
(error) => { return throw error; }
throw is a statement not expression , that's why it is not valid. So you have to define like below:
(error) => {throw error};
Upvotes: 2
Reputation: 370699
throw
is a statement (something that does something), and not an expression (which evaluates to a value).
When using concise body syntax - an arrow function without a {
following =>
- what follows the =>
must be an expression. So, (error) => throw error
doesn't work - your only option is to put the throw
in the context of somewhere where an expression is permitted, which will have to be inside a block:
(error) => {
throw error
}
You can put it all on one line if you want, but the brackets will still be required:
(error) => { throw error }
I suppose you could use a concise body for the outer function and put in an IIFE which makes a new block, inside of which throw
will be permitted, but that adds syntax noise for no real gain IMO:
(error) => (() => { throw error })();
Throw expressions are at stage 2. Eventually, it may well be possible to use throw
like you want, with a concise body - but it's not possible quite yet.
Upvotes: 4