Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the 'catch' method name of JS Promises/A+ invalid since it's a JS keyword?

I started to use JS Promises in a project recently. I noticed that every time I use .catch my JS linter complains. It does run and does what it should but I looked up the ECMAScript spec and it really looks like it is right: Since catch is a keyword it can not be used as an identifier. As I understand method names are identifiers, so this is invalid:

Promise.reject("Duh").catch(alert);

It should be this instead:

Promise.reject("Duh")['catch'](alert);

What am I missing?

like image 958
Fozi Avatar asked Sep 10 '14 20:09

Fozi


People also ask

Does catch return a promise?

catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.

How do you catch errors with promises?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.

What are JavaScript promises?

A Promise is a JavaScript object that links producing code and consuming code.

When were promises added to JavaScript?

Promises were introduced to the JavaScript language in the ES6 version in 2015, and support is now widespread. Node. js supports them, and all major web browsers except Internet Explorer and Opera Mini have implemented them as well (see the browser support matrix for details).


1 Answers

What am I missing?

A property name is not an identifier, it can use any identifier name. From the spec on Property Accessors:

MemberExpression : MemberExpression . IdentifierName
CallExpression : CallExpression . IdentifierName

and identifiers:

Identifier :: IdentifierName but not ReservedWord

You can use any arbitrary identifer name (but not things like integers) in a dot property access, but you can't use those that are [reserved] keywords as identifier, e.g. in a variable or function name.

However, this did change with ES5, back in EcmaScript 3 property names were required to be identiers. That's why you still need to use the bracket notation for keywords if you want to support legacy browsers; and it's the reason why your linter complains about it. Same holds for property names in object literals.

like image 154
Bergi Avatar answered Oct 01 '22 20:10

Bergi