runtimeZero runtimeZero - 2 months ago 13
Javascript Question

ES6 syntax : what is this an error : .catch(err => throw err);

The following code works FINE:

pool.getConnection()
.then((conn)=>{
// something here
})
.catch((err) => {
throw err;
});


However node throws error when I reformat it as such:

return pool.getConnection()
.then((conn) => {
//something here
})
.then(results => results[0].insertId)
.catch(err => throw err); <-- NODE COMPALINS HERE


$>somefile.js line(190)
.catch(err => throw err);
^^^^^
SyntaxError: Unexpected token throw


What am I missing here ?

Answer

An arrow function has a behavior where, if you don't put {} after it, it has an implicit return.

So your code is essentially this:

.catch(err => { return throw err; });

You can only return expressions, and cannot return statements like throw.

function test(e) {
  return throw e; // syntax error
}

Comments