-
-
Notifications
You must be signed in to change notification settings - Fork 91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(rule): add prefer-promise-static-methods
rule
#473
Open
NotWoods
wants to merge
1
commit into
eslint-community:main
Choose a base branch
from
NotWoods:prefer-promise-static-methods
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
'use strict' | ||
|
||
const rule = require('../rules/prefer-promise-static-methods') | ||
const { RuleTester } = require('./rule-tester') | ||
const ruleTester = new RuleTester({ | ||
parserOptions: { | ||
ecmaVersion: 6, | ||
}, | ||
}) | ||
|
||
const resolveErrorMessage = | ||
'Prefer `Promise.resolve()` to `new Promise()`. The static method is faster, more readable and less verbose.' | ||
const rejectErrorMessage = | ||
'Prefer `Promise.reject()` to `new Promise()`. The static method is faster, more readable and less verbose.' | ||
|
||
ruleTester.run('prefer-promise-static-methods', rule, { | ||
valid: [ | ||
`Promise.resolve(foo)`, | ||
`Promise.reject(bar)`, | ||
`new Promise(() => {})`, | ||
`new Promise((resolve) => setTimeout(resolve, 100))`, | ||
`new Promise(process.nextTick)`, | ||
`new Promise((resolve) => { resolve(foo); resolve(bar) })`, | ||
`new Promise((resolve, reject) => { foo(bar) })`, | ||
`new Promise((resolve, reject) => { foo && resolve(bar) })`, | ||
`new Promise((...args) => {})`, | ||
// This is a type error but the rule wouldn't check it | ||
`new Promise(([foo, bar]) => {})`, | ||
`new Promise(([foo, bar] = []) => {})`, | ||
], | ||
|
||
invalid: [ | ||
{ | ||
code: `new Promise((resolve) => resolve(foo))`, | ||
output: `Promise.resolve(foo)`, | ||
errors: [{ message: resolveErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise((resolve) => { resolve(foo) })`, | ||
output: `Promise.resolve(foo)`, | ||
errors: [{ message: resolveErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise((resolve) => resolve())`, | ||
output: `Promise.resolve()`, | ||
errors: [{ message: resolveErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise((_, reject) => reject(foo))`, | ||
output: `Promise.reject(foo)`, | ||
errors: [{ message: rejectErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise((resolve, reject) => { reject(foo) })`, | ||
output: `Promise.reject(foo)`, | ||
errors: [{ message: rejectErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise(function foo(resolve, reject) { reject(bar) })`, | ||
output: `Promise.reject(bar)`, | ||
errors: [{ message: rejectErrorMessage }], | ||
}, | ||
{ | ||
code: `new Promise((resolve = unusedDefault) => resolve())`, | ||
output: `Promise.resolve()`, | ||
errors: [{ message: resolveErrorMessage }], | ||
}, | ||
], | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# Prefer `Promise.resolve(foo)` to `new Promise((resolve) => resolve(foo))` (`promise/prefer-promise-static-methods`) | ||
|
||
🔧 This rule is automatically fixable by the | ||
[`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). | ||
|
||
<!-- end auto-generated rule header --> | ||
|
||
Using `new Promise()` for simple use cases is a common mistake when developers | ||
first start working with promises. When `resolve` or `reject` is immediately | ||
called in the promise executor, it's better to just use the static | ||
`Promise.resolve()` or `Promise.reject()` methods. The static methods are | ||
faster, more readable and less verbose. | ||
|
||
#### Valid | ||
|
||
```js | ||
Promise.resolve(foo) | ||
Promise.reject(bar) | ||
|
||
new Promise((resolve) => setTimeout(resolve, 100)) | ||
new Promise((resolve, reject) => { | ||
if (foo) { | ||
resolve(bar) | ||
} | ||
}) | ||
``` | ||
|
||
#### Invalid | ||
|
||
```js | ||
new Promise((resolve) => resolve(foo)) | ||
new Promise((resolve) => { | ||
resolve(foo) | ||
}) | ||
// autofix to Promise.resolve(foo); | ||
|
||
new Promise((_, reject) => reject(foo)) | ||
new Promise(function (_, reject) { | ||
reject(foo) | ||
}) | ||
// autofix to Promise.reject(foo); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/** | ||
* Rule: prefer-promise-static-methods | ||
* Prefer `Promise.resolve(foo)` to `new Promise((resolve) => resolve(foo))`. | ||
*/ | ||
|
||
'use strict' | ||
|
||
const { getSourceCode } = require('./lib/eslint-compat') | ||
const getDocsUrl = require('./lib/get-docs-url') | ||
const { | ||
isPromiseConstructorWithInlineExecutor, | ||
} = require('./lib/is-promise-constructor') | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: | ||
'Prefer `Promise.resolve(foo)` to `new Promise((resolve) => resolve(foo))`.', | ||
url: getDocsUrl('prefer-promise-static-methods'), | ||
}, | ||
messages: { | ||
replaceWithStaticMethod: | ||
'Prefer `Promise.{{ method }}()` to `new Promise()`. The static method is faster, more readable and less verbose.', | ||
}, | ||
fixable: 'code', | ||
schema: [], | ||
}, | ||
create(context) { | ||
const sourceCode = getSourceCode(context) | ||
/** | ||
* Report an error if the given node is a call to `resolve` or `reject`. | ||
* @param {import('estree').SimpleCallExpression} callNode | ||
* @param {import('estree').NewExpression} constructorNode | ||
* @param {Array<string | undefined>} parameterNames | ||
*/ | ||
function reportIfIsPromiseCall(callNode, constructorNode, parameterNames) { | ||
if ( | ||
callNode.callee.type === 'Identifier' && | ||
callNode.arguments.length <= 1 | ||
) { | ||
/** @type {'resolve' | 'reject'} */ | ||
let method | ||
if (callNode.callee.name === parameterNames[0]) { | ||
method = 'resolve' | ||
} else if (callNode.callee.name === parameterNames[1]) { | ||
method = 'reject' | ||
} else { | ||
return | ||
} | ||
|
||
// Value passed to resolve/reject method | ||
const valueNode = callNode.arguments[0] | ||
const valueText = valueNode | ||
? sourceCode.getText(callNode.arguments[0]) | ||
: '' | ||
context.report({ | ||
node: callNode, | ||
messageId: 'replaceWithStaticMethod', | ||
data: { method }, | ||
fix: (fixer) => | ||
fixer.replaceText( | ||
constructorNode, | ||
`Promise.${method}(${valueText})` | ||
), | ||
}) | ||
} | ||
} | ||
|
||
return { | ||
NewExpression(node) { | ||
if (isPromiseConstructorWithInlineExecutor(node)) { | ||
const func = node.arguments[0] | ||
const parameterNames = getParameterNames(func.params) | ||
|
||
if (func.body.type === 'CallExpression') { | ||
// (resolve) => resolve(foo) | ||
reportIfIsPromiseCall(func.body, node, parameterNames) | ||
} else if ( | ||
func.body.type === 'BlockStatement' && | ||
func.body.body.length === 1 | ||
) { | ||
const statement = func.body.body[0] | ||
if ( | ||
statement.type === 'ExpressionStatement' && | ||
statement.expression.type === 'CallExpression' | ||
) { | ||
// (resolve) => { resolve(foo) } | ||
reportIfIsPromiseCall(statement.expression, node, parameterNames) | ||
} | ||
} | ||
} | ||
}, | ||
} | ||
}, | ||
} | ||
|
||
/** | ||
* Given AST for `(resolve, reject) => {...}` params, return `['resolve', 'reject']`. | ||
* @param {import('estree').Pattern[]} params | ||
*/ | ||
function getParameterNames(params) { | ||
/** @type {Array<string | undefined>} */ | ||
const names = [] | ||
for (const param of params) { | ||
switch (param.type) { | ||
// (resolve) => | ||
case 'Identifier': | ||
names.push(param.name) | ||
break | ||
// (resolve = foo) => | ||
case 'AssignmentPattern': | ||
if (param.left.type === 'Identifier') { | ||
names.push(param.left.name) | ||
} else { | ||
names.push(undefined) | ||
} | ||
break | ||
// (...args) => | ||
case 'RestElement': | ||
// there won't be any more valid names | ||
return names | ||
// ([resolve]) => | ||
default: | ||
names.push(undefined) | ||
break | ||
} | ||
} | ||
|
||
return names | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about
new Promise(resolve => resolve(itCanThrowAnError()))
(the case ofPromise.try
)?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm I'm not sure what the best approach there would be. (Also I didn't realize
new Promise
is same tick, I must've misread the spec.) Perhaps just show a suggestion instead of an autofix?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that cases that could throw an error should be ignored (however, it's too many possible cases - I think that it's OK to ignore only call and new). Also, can be added an option to check such cases, without autofixes.