From a104a850f892181c42ad2fb2e8809f1331b9ee73 Mon Sep 17 00:00:00 2001 From: Anix Date: Wed, 25 Mar 2020 19:18:32 +0000 Subject: [PATCH] fix: ignores iife for no-floating-promise (fixes #647) --- .../src/rules/no-floating-promises.ts | 18 ++++++++++++ .../tests/rules/no-floating-promises.test.ts | 28 ++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/packages/eslint-plugin/src/rules/no-floating-promises.ts b/packages/eslint-plugin/src/rules/no-floating-promises.ts index c3ee7ffccf3c..2c5a41b10d65 100644 --- a/packages/eslint-plugin/src/rules/no-floating-promises.ts +++ b/packages/eslint-plugin/src/rules/no-floating-promises.ts @@ -12,6 +12,11 @@ type Options = [ type MessageId = 'floating' | 'floatingVoid' | 'floatingFixVoid'; +const possibleIifeCalleType = new Set([ + 'FunctionExpression', + 'ArrowFunctionExpression', +]); + export default util.createRule({ name: 'no-floating-promises', meta: { @@ -54,6 +59,10 @@ export default util.createRule({ ExpressionStatement(node): void { const { expression } = parserServices.esTreeNodeToTSNodeMap.get(node); + if (isIife(node)) { + return; + } + if (isUnhandledPromise(checker, expression)) { if (options.ignoreVoid) { context.report({ @@ -80,6 +89,15 @@ export default util.createRule({ }, }; + function isIife(node: ts.Node): Boolean { + if (node?.expression.type === 'CallExpression') { + if (possibleIifeCalleType.has(node?.expression?.callee.type)) { + return true; + } + } + return false; + } + function isUnhandledPromise( checker: ts.TypeChecker, node: ts.Node, diff --git a/packages/eslint-plugin/tests/rules/no-floating-promises.test.ts b/packages/eslint-plugin/tests/rules/no-floating-promises.test.ts index efdbf5e1a48c..10bafefa7cee 100644 --- a/packages/eslint-plugin/tests/rules/no-floating-promises.test.ts +++ b/packages/eslint-plugin/tests/rules/no-floating-promises.test.ts @@ -251,6 +251,30 @@ async function test() { return returnsPromise(); } `, + ` +(async () => { + await something(); +})(); +`, + ` +(async () => { + something(); +})(); +`, + '(async function foo(){})();', + ` +function foo(){ + (async function bar() { + })() +} +`, + ` + const foo = () => new Promise((res) => { + (async function(){ + await res(1) + })() + }) +`, ], invalid: [ @@ -344,10 +368,6 @@ async function test() { } `, errors: [ - { - line: 3, - messageId: 'floating', - }, { line: 4, messageId: 'floating',