summaryrefslogtreecommitdiff
path: root/tools/eslint-rules/async-iife-no-unused-result.js
blob: bb089de8832d8843ea7a59230792a1ec2f1edf55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'use strict';
const { isCommonModule } = require('./rules-utils.js');

function isAsyncIIFE(node) {
  const { callee: { type, async } } = node;
  const types = ['FunctionExpression', 'ArrowFunctionExpression'];
  return types.includes(type) && async;
}

const message =
  'The result of an immediately-invoked async function needs to be used ' +
  '(e.g. with `.then(common.mustCall())`)';

module.exports = {
  meta: {
    fixable: 'code'
  },
  create: function(context) {
    let hasCommonModule = false;
    return {
      CallExpression: function(node) {
        if (isCommonModule(node) && node.parent.type === 'VariableDeclarator') {
          hasCommonModule = true;
        }

        if (!isAsyncIIFE(node)) return;
        if (node.parent && node.parent.type === 'ExpressionStatement') {
          context.report({
            node,
            message,
            fix: (fixer) => {
              if (hasCommonModule)
                return fixer.insertTextAfter(node, '.then(common.mustCall())');
            }
          });
        }
      }
    };
  }
};