Skip to content

Commit

Permalink
feat(eslint-plugin): add new rule no-floating-promises
Browse files Browse the repository at this point in the history
Adds the equivalent of TSLint's `no-floating-promises` rule. Fixes #464
  • Loading branch information
princjef committed May 6, 2019
1 parent 6ccf482 commit f897a68
Show file tree
Hide file tree
Showing 5 changed files with 616 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -132,6 +132,7 @@ Then you should add `airbnb` (or `airbnb-base`) to your `extends` section of `.e
| [`@typescript-eslint/no-explicit-any`](./docs/rules/no-explicit-any.md) | Disallow usage of the `any` type (`no-any` from TSLint) | :heavy_check_mark: | | |
| [`@typescript-eslint/no-extra-parens`](./docs/rules/no-extra-parens.md) | Disallow unnecessary parentheses | | :wrench: | |
| [`@typescript-eslint/no-extraneous-class`](./docs/rules/no-extraneous-class.md) | Forbids the use of classes as namespaces (`no-unnecessary-class` from TSLint) | | | |
| [`@typescript-eslint/no-floating-promises`](./docs/rules/no-floating-promises.md) | Requires Promise-like values to be handled appropriately. | | | :thought_balloon: |
| [`@typescript-eslint/no-for-in-array`](./docs/rules/no-for-in-array.md) | Disallow iterating over an array with a for-in loop (`no-for-in-array` from TSLint) | | | :thought_balloon: |
| [`@typescript-eslint/no-inferrable-types`](./docs/rules/no-inferrable-types.md) | Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean. (`no-inferrable-types` from TSLint) | :heavy_check_mark: | :wrench: | |
| [`@typescript-eslint/no-misused-new`](./docs/rules/no-misused-new.md) | Enforce valid definition of `new` and `constructor`. (`no-misused-new` from TSLint) | :heavy_check_mark: | | |
Expand Down
5 changes: 3 additions & 2 deletions packages/eslint-plugin/ROADMAP.md
@@ -1,4 +1,4 @@
# Roadmap
# Roadmap

✅ = done<br>
🌟 = in ESLint core<br>
Expand Down Expand Up @@ -60,7 +60,7 @@
| [`no-dynamic-delete`] | 🛑 | N/A |
| [`no-empty`] | 🌟 | [`no-empty`][no-empty] |
| [`no-eval`] | 🌟 | [`no-eval`][no-eval] |
| [`no-floating-promises`] | 🛑 | N/A ([relevant plugin][plugin:promise]) |
| [`no-floating-promises`] | | [`@typescript-eslint/no-floating-promises`] |
| [`no-for-in-array`] || [`@typescript-eslint/no-for-in-array`] |
| [`no-implicit-dependencies`] | 🔌 | [`import/no-extraneous-dependencies`] |
| [`no-inferred-empty-object-type`] | 🛑 | N/A |
Expand Down Expand Up @@ -612,6 +612,7 @@ Relevant plugins: [`chai-expect-keywords`](https://github.com/gavinaiken/eslint-
[`@typescript-eslint/no-for-in-array`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-for-in-array.md
[`@typescript-eslint/no-unnecessary-qualifier`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unnecessary-qualifier.md
[`@typescript-eslint/semi`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/semi.md
[`@typescript-eslint/no-floating-promises`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-floating-promises.md

<!-- eslint-plugin-import -->

Expand Down
46 changes: 46 additions & 0 deletions packages/eslint-plugin/docs/rules/no-floating-promises.md
@@ -0,0 +1,46 @@
# Requires Promise-like values to be handled appropriately (no-floating-promises)

This rule forbids usage of Promise-like values in statements without handling
their errors appropriately. Unhandled promises can cause several issues, such
as improperly sequenced operations, ignored Promise rejections and more. Valid
ways of handling a Promise-valued statement include `await`ing, returning, and
either calling `.then()` with two arguments or `.catch()` with one argument.

## Rule Details

Examples of **incorrect** code for this rule:

```ts
const promise = new Promise((resolve, reject) => resolve('value'));
promise;

async function returnsPromise() {
return 'value';
}
returnsPromise().then(() => {});

Promise.reject('value').catch();
```

Examples of **correct** code for this rule:

```ts
const promise = new Promise((resolve, reject) => resolve('value'));
await promise;

async function returnsPromise() {
return 'value';
}
returnsPromise().then(() => {}, () => {});

Promise.reject('value').catch(() => {});
```

## When Not To Use It

If you do not use Promise-like values in your codebase or want to allow them to
remain unhandled.

## Related to

- Tslint: ['no-floating-promises'](https://palantir.github.io/tslint/rules/no-floating-promises/)
127 changes: 127 additions & 0 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
@@ -0,0 +1,127 @@
import * as tsutils from 'tsutils';
import * as ts from 'typescript';

import * as util from '../util';

export default util.createRule({
name: 'no-floating-promises',
meta: {
docs: {
description:
'Requires promises to be awaited or have a rejection handler.',
category: 'Best Practices',
recommended: false,
tslintName: 'no-floating-promises',
},
messages: {
floating: 'Promises must be handled appropriately',
},
schema: [],
type: 'problem',
},
defaultOptions: [],

create(context) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();

return {
ExpressionStatement(node) {
const { expression } = parserServices.esTreeNodeToTSNodeMap.get(
node,
) as ts.ExpressionStatement;
const type = checker.getTypeAtLocation(expression);

if (
isPromiseLike(checker, expression, type) &&
(!tsutils.isCallExpression(expression) ||
(!isPromiseCatchCallWithHandler(expression) &&
!isPromiseThenCallWithRejectionHandler(expression)))
) {
context.report({
messageId: 'floating',
node,
});
}
},
};
},
});

// Modified from tsutils.isThenable() to only consider thenables which can be
// rejected/caught via a second parameter. Original source (MIT licensed):
//
// https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125
function isPromiseLike(
checker: ts.TypeChecker,
node: ts.Node,
type: ts.Type,
): boolean {
for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
}

const thenType = checker.getTypeOfSymbolAtLocation(then, node);
if (
hasMatchingSignature(
thenType,
signature =>
signature.parameters.length >= 2 &&
isFunctionParam(checker, signature.parameters[0], node) &&
isFunctionParam(checker, signature.parameters[1], node),
)
) {
return true;
}
}
return false;
}

function hasMatchingSignature(
type: ts.Type,
matcher: (signature: ts.Signature) => boolean,
): boolean {
for (const t of tsutils.unionTypeParts(type)) {
if (t.getCallSignatures().some(matcher)) {
return true;
}
}

return false;
}

function isFunctionParam(
checker: ts.TypeChecker,
param: ts.Symbol,
node: ts.Node,
): boolean {
let type: ts.Type | undefined = checker.getApparentType(
checker.getTypeOfSymbolAtLocation(param, node),
);
for (const t of tsutils.unionTypeParts(type)) {
if (t.getCallSignatures().length !== 0) {
return true;
}
}
return false;
}

function isPromiseCatchCallWithHandler(expression: ts.CallExpression): boolean {
return (
tsutils.isPropertyAccessExpression(expression.expression) &&
expression.expression.name.text === 'catch' &&
expression.arguments.length >= 1
);
}

function isPromiseThenCallWithRejectionHandler(
expression: ts.CallExpression,
): boolean {
return (
tsutils.isPropertyAccessExpression(expression.expression) &&
expression.expression.name.text === 'then' &&
expression.arguments.length >= 2
);
}

0 comments on commit f897a68

Please sign in to comment.