Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
feat(eslint-plugin): added new rule await-promise#192
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
bradzacher merged 24 commits intotypescript-eslint:masterfromJoshuaKGoldberg:typescript-eslint-await-promiseApr 11, 2019
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
24 commits Select commitHold shift + click to select a range
951a4fc
feat(eslint-plugin) Added await-promise rule
c821cc1
Update packages/eslint-plugin/docs/rules/await-promise.md
j-f15a3def8
Merge branch 'master'; moved type util to utils/types.js
62a6a71
Fixed formatting complaint, I think?
d40d23c
Merge branch 'master'
7c386cc
Whoops, docs typo
c899d72
Merge branch 'master'
5316313
30 done, not 29
b93f223
Merge branch 'master' into typescript-eslint-await-promise
db672a9
Merge branch 'master' into typescript-eslint-await-promise
bradzacher562fe93
Merge branch 'master'
b8bd73e
Fixed ROADMAP.md links for await-promise
3646331
Removed async iterable checking
bcce472
Merge branch 'master' into typescript-eslint-await-promise
d5726e6
Converted to TypeScript; used tsutils.isThenableType
61cfe81
Update packages/eslint-plugin/README.md
mysticatea30585b3
Update packages/eslint-plugin/docs/rules/await-thenable.md
mysticatea4731cd3
Update packages/eslint-plugin/ROADMAP.md
mysticatea89ab9ba
Update packages/eslint-plugin/ROADMAP.md
mysticatea9e66704
Merge branch 'master'
addce1d
Docs touchups as requested
fc74dda
Merge branch 'master' into typescript-eslint-await-promise
JamesHenry85fdeb0
Merge branch 'master' into typescript-eslint-await-promise
bradzacherd59c57e
Merge branch 'master' into typescript-eslint-await-promise
bradzacherFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletionspackages/eslint-plugin/README.md
This file contains hidden or 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
3 changes: 2 additions & 1 deletionpackages/eslint-plugin/ROADMAP.md
This file contains hidden or 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
33 changes: 33 additions & 0 deletionspackages/eslint-plugin/docs/rules/await-thenable.md
This file contains hidden or 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,33 @@ | ||
# Disallows awaiting a value that is not a Promise (await-thenable) | ||
This rule disallows awaiting a value that is not a "Thenable" (an object which has `then` method, such as a Promise). | ||
While it is valid JavaScript to await a non-`Promise`-like value (it will resolve immediately), this pattern is often a programmer error, such as forgetting to add parenthesis to call a function that returns a Promise. | ||
## Rule Details | ||
Examples of **incorrect** code for this rule: | ||
```ts | ||
await 'value'; | ||
const createValue = () => 'value'; | ||
await createValue(); | ||
``` | ||
Examples of **correct** code for this rule: | ||
```ts | ||
await Promise.resolve('value'); | ||
const createValue = async () => 'value'; | ||
await createValue(); | ||
``` | ||
## When Not To Use It | ||
If you want to allow code to `await` non-Promise values. | ||
This is generally not preferred, but can sometimes be useful for visual consistency. | ||
## Related to | ||
- TSLint: ['await-promise'](https://palantir.github.io/tslint/rules/await-promise) |
47 changes: 47 additions & 0 deletionspackages/eslint-plugin/src/rules/await-thenable.ts
This file contains hidden or 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,47 @@ | ||
import * as tsutils from 'tsutils'; | ||
import * as ts from 'typescript'; | ||
import * as util from '../util'; | ||
export default util.createRule({ | ||
name: 'await-thenable', | ||
meta: { | ||
docs: { | ||
description: 'Disallows awaiting a value that is not a Thenable', | ||
category: 'Best Practices', | ||
recommended: 'error', | ||
tslintName: 'await-thenable', | ||
}, | ||
messages: { | ||
await: 'Unexpected `await` of a non-Promise (non-"Thenable") value.', | ||
}, | ||
schema: [], | ||
type: 'problem', | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
const parserServices = util.getParserServices(context); | ||
const checker = parserServices.program.getTypeChecker(); | ||
return { | ||
AwaitExpression(node) { | ||
const originalNode = parserServices.esTreeNodeToTSNodeMap.get( | ||
node, | ||
) as ts.AwaitExpression; | ||
const type = checker.getTypeAtLocation(originalNode.expression); | ||
if ( | ||
!tsutils.isTypeFlagSet(type, ts.TypeFlags.Any) && | ||
!tsutils.isTypeFlagSet(type, ts.TypeFlags.Unknown) && | ||
!tsutils.isThenableType(checker, originalNode.expression, type) | ||
) { | ||
context.report({ | ||
messageId: 'await', | ||
node, | ||
}); | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
223 changes: 223 additions & 0 deletionspackages/eslint-plugin/tests/rules/await-thenable.test.ts
This file contains hidden or 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,223 @@ | ||
import rule from '../../src/rules/await-thenable'; | ||
import { RuleTester, getFixturesRootDir } from '../RuleTester'; | ||
const rootDir = getFixturesRootDir(); | ||
const parserOptions = { | ||
ecmaVersion: 2018, | ||
tsconfigRootDir: rootDir, | ||
project: './tsconfig.json', | ||
}; | ||
const messageId = 'await'; | ||
const ruleTester = new RuleTester({ | ||
parserOptions, | ||
parser: '@typescript-eslint/parser', | ||
}); | ||
ruleTester.run('await-promise', rule, { | ||
valid: [ | ||
` | ||
async function test() { | ||
await Promise.resolve("value"); | ||
await Promise.reject(new Error("message")); | ||
} | ||
`, | ||
` | ||
async function test() { | ||
await (async () => true)(); | ||
} | ||
`, | ||
` | ||
async function test() { | ||
function returnsPromise() { | ||
return Promise.resolve("value"); | ||
} | ||
await returnsPromise(); | ||
} | ||
`, | ||
` | ||
async function test() { | ||
async function returnsPromiseAsync() {} | ||
await returnsPromiseAsync(); | ||
} | ||
`, | ||
` | ||
async function test() { | ||
let anyValue: any; | ||
await anyValue; | ||
} | ||
`, | ||
` | ||
async function test() { | ||
let unknownValue: unknown; | ||
await unknownValue; | ||
} | ||
`, | ||
` | ||
async function test() { | ||
const numberPromise: Promise<number>; | ||
await numberPromise; | ||
} | ||
`, | ||
` | ||
async function test() { | ||
class Foo extends Promise<number> {} | ||
const foo: Foo = Foo.resolve(2); | ||
await foo; | ||
class Bar extends Foo {} | ||
const bar: Bar = Bar.resolve(2); | ||
await bar; | ||
} | ||
`, | ||
` | ||
async function test() { | ||
await (Math.random() > 0.5 ? numberPromise : 0); | ||
await (Math.random() > 0.5 ? foo : 0); | ||
await (Math.random() > 0.5 ? bar : 0); | ||
const intersectionPromise: Promise<number> & number; | ||
await intersectionPromise; | ||
} | ||
`, | ||
` | ||
async function test() { | ||
class Thenable { then(callback: () => {}) { } }; | ||
const thenable = new Thenable(); | ||
await thenable; | ||
} | ||
`, | ||
` | ||
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/promise-polyfill/index.d.ts | ||
// Type definitions for promise-polyfill 6.0 | ||
// Project: https://github.com/taylorhakes/promise-polyfill | ||
// Definitions by: Steve Jenkins <https://github.com/skysteve> | ||
// Daniel Cassidy <https://github.com/djcsdy> | ||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | ||
interface PromisePolyfillConstructor extends PromiseConstructor { | ||
_immediateFn?: (handler: (() => void) | string) => void; | ||
} | ||
declare const PromisePolyfill: PromisePolyfillConstructor; | ||
async function test() { | ||
const promise = new PromisePolyfill(() => {}); | ||
await promise; | ||
} | ||
`, | ||
` | ||
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/bluebird/index.d.ts | ||
// Type definitions for bluebird 3.5 | ||
// Project: https://github.com/petkaantonov/bluebird | ||
// Definitions by: Leonard Hecker <https://github.com/lhecker> | ||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | ||
// TypeScript Version: 2.8 | ||
/*! | ||
* The code following this comment originates from: | ||
* https://github.com/types/npm-bluebird | ||
* | ||
* Note for browser users: use bluebird-global typings instead of this one | ||
* if you want to use Bluebird via the global Promise symbol. | ||
* | ||
* Licensed under: | ||
* The MIT License (MIT) | ||
* | ||
* Copyright (c) 2016 unional | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
type Constructor<E> = new (...args: any[]) => E; | ||
type CatchFilter<E> = ((error: E) => boolean) | (object & E); | ||
type IterableItem<R> = R extends Iterable<infer U> ? U : never; | ||
type IterableOrNever<R> = Extract<R, Iterable<any>>; | ||
type Resolvable<R> = R | PromiseLike<R>; | ||
type IterateFunction<T, R> = (item: T, index: number, arrayLength: number) => Resolvable<R>; | ||
declare class Bluebird<R> implements PromiseLike<R> { | ||
then<U>(onFulfill?: (value: R) => Resolvable<U>, onReject?: (error: any) => Resolvable<U>): Bluebird<U>; // For simpler signature help. | ||
then<TResult1 = R, TResult2 = never>( | ||
onfulfilled?: ((value: R) => Resolvable<TResult1>) | null, | ||
onrejected?: ((reason: any) => Resolvable<TResult2>) | null | ||
): Bluebird<TResult1 | TResult2>; | ||
} | ||
declare const bluebird: Bluebird; | ||
async function test() { | ||
await bluebird; | ||
} | ||
`, | ||
], | ||
invalid: [ | ||
{ | ||
code: ` | ||
async function test() { | ||
await 0; | ||
await "value"; | ||
await (Math.random() > 0.5 ? "" : 0); | ||
class NonPromise extends Array {} | ||
await new NonPromise(); | ||
} | ||
`, | ||
errors: [ | ||
{ | ||
line: 3, | ||
messageId, | ||
}, | ||
{ | ||
line: 4, | ||
messageId, | ||
}, | ||
{ | ||
line: 6, | ||
messageId, | ||
}, | ||
{ | ||
line: 9, | ||
messageId, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: ` | ||
async function test() { | ||
class IncorrectThenable { then() { } }; | ||
const thenable = new IncorrectThenable(); | ||
await thenable; | ||
} | ||
`, | ||
errors: [ | ||
{ | ||
line: 6, | ||
messageId, | ||
}, | ||
], | ||
}, | ||
], | ||
}); |
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.