File tree Expand file tree Collapse file tree 4 files changed +82
-0
lines changed Expand file tree Collapse file tree 4 files changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ # No ` Promise.then `
2+
3+ Yes, you should use promises, but prefer ` async ` /` await ` syntax instead of ` Promise.then() ` callback chaining.
4+
5+ ``` js
6+ // bad
7+ function getProcessedData (url ) {
8+ return downloadData (url)
9+ .catch (e => {
10+ return downloadFallbackData (url)
11+ })
12+ .then (v => {
13+ return processDataInWorker (v)
14+ })
15+ }
16+
17+ // good
18+ async function getProcessedData (url ) {
19+ let v
20+ try {
21+ v = await downloadData (url)
22+ } catch (e) {
23+ v = await downloadFallbackData (url)
24+ }
25+ return processDataInWorker (v)
26+ }
27+ ```
28+
29+ ## See Also
30+
31+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Original file line number Diff line number Diff line change @@ -13,6 +13,7 @@ module.exports = {
1313 ] ,
1414 'rules' : {
1515 'github/array-foreach' : 'error' ,
16+ 'github/no-then' : 'error' ,
1617 'import/default' : 'error' ,
1718 'import/export' : 'error' ,
1819 'import/first' : 'error' ,
Original file line number Diff line number Diff line change 1+ module . exports = function ( context ) {
2+ return {
3+ MemberExpression : function ( node ) {
4+ if ( node . property && node . property . name === 'then' ) {
5+ context . report ( node . property , 'Prefer async/await to Promise.then()' )
6+ } else if ( node . property && node . property . name === 'catch' ) {
7+ context . report ( node . property , 'Prefer async/await to Promise.catch()' )
8+ }
9+ }
10+ }
11+ }
Original file line number Diff line number Diff line change 1+ var rule = require ( '../lib/rules/no-then' )
2+ var RuleTester = require ( 'eslint' ) . RuleTester
3+
4+ var ruleTester = new RuleTester ( )
5+
6+ ruleTester . run ( 'no-then' , rule , {
7+ valid : [
8+ {
9+ code : '(async function() { const data = await read(); console.log(data) })()' ,
10+ parserOptions : { ecmaVersion : 2017 }
11+ } ,
12+ {
13+ code : '(async function() { try { await read() } catch(error) { console.error(error) } })()' ,
14+ parserOptions : { ecmaVersion : 2017 }
15+ }
16+ ] ,
17+ invalid : [
18+ {
19+ code : '(function() { read().then(data => console.log(data)) })()' ,
20+ parserOptions : { ecmaVersion : 2017 } ,
21+ errors : [
22+ {
23+ message : 'Prefer async/await to Promise.then()' ,
24+ type : 'Identifier'
25+ }
26+ ]
27+ } ,
28+ {
29+ code : '(function() { read().catch(error => console.error(error)) })()' ,
30+ parserOptions : { ecmaVersion : 2017 } ,
31+ errors : [
32+ {
33+ message : 'Prefer async/await to Promise.catch()' ,
34+ type : 'Identifier'
35+ }
36+ ]
37+ }
38+ ]
39+ } )
You can’t perform that action at this time.
0 commit comments