如何用ESLint校验JavaScript Promise语法(含拼写错误检测)
then/catch Spelling Errors (Universal & Atom-Friendly) Hey there! Great question—catching typos like thedn or casch in Promise chains is crucial to avoid frustrating silent bugs. Below are practical, cross-editor solutions, plus a few Atom-specific tweaks to make this seamless:
1. Use ESLint (Most Universal Solution)
ESLint is the go-to static code analyzer for JavaScript, and it can easily flag invalid Promise method names. Here's how to set it up:
- Install ESLint and the promise-focused plugin via npm:
npm install eslint eslint-plugin-promise --save-dev - Create or update your
.eslintrc.jsonconfig file to enable rules that catch invalid Promise properties:
This will throw an error whenever you try to access a non-existent method like{ "plugins": ["promise"], "rules": { "promise/valid-params": "error", "no-undef": "error", "no-unknown-property": ["error", { "objects": ["Promise.prototype"] }] } }thednon a Promise instance. Most editors (including Atom) can integrate ESLint to show these errors in real-time.
2. Leverage TypeScript Type Checking
If you're open to using TypeScript (or even renaming your .js files to .ts for type checks), it'll automatically flag invalid Promise method calls. TypeScript knows exactly what methods exist on the Promise type, so typos like casch will trigger an immediate error:
- Set up a basic
tsconfig.jsonin your project:
Most editors (Atom included with the{ "compilerOptions": { "strict": true, "noImplicitAny": true, "allowJs": true // If you want to check regular JS files } }atom-typescriptplugin) will show these type errors right in the editor gutter.
3. Atom-Specific Integration
To bring the above solutions into Atom for real-time feedback:
- Install the
linter-eslintplugin via Atom's Settings → Install tab. This connects ESLint to Atom, showing errors directly in your editor. - For TypeScript support, install the
atom-typescriptplugin—it will automatically pick up yourtsconfig.jsonand highlight invalid Promise method names.
4. Prevent Typos with Code Snippets
Instead of catching typos after the fact, avoid them entirely with editor snippets. In Atom:
- Go to Settings → Snippets.
- Add this snippet for quick, correct Promise chain insertion:
Now, typing'.source.js, .source.ts': 'Promise Then/Catch Chain': 'prefix': 'promise-chain' 'body': """ .then(${1:(value) => { $0 }}) .catch(${2:(error) => { console.error(error); }}) """promise-chainand hitting tab will insert a perfectly spelledthen/catchblock, ready for your code.
These solutions work across nearly all modern editors (VS Code, Sublime, etc.)—the ESLint and TypeScript setups are completely editor-agnostic, while snippets can be adapted to any editor's snippet system.
内容的提问来源于stack exchange,提问作者Jamo

