diff --git a/__tests__/prefer-await-to-then.js b/__tests__/prefer-await-to-then.js index 3bdf5bd8..2770c7b2 100644 --- a/__tests__/prefer-await-to-then.js +++ b/__tests__/prefer-await-to-then.js @@ -15,6 +15,8 @@ ruleTester.run('prefer-await-to-then', rule, { 'async function hi() { await thing() }', 'async function hi() { await thing().then() }', 'async function hi() { await thing().catch() }', + 'async function hi() { await thing().finally() }', + 'function * hi() { yield thing().then() }', 'a = async () => (await something())', `a = async () => { try { await something() } catch (error) { somethingElse() } @@ -54,5 +56,41 @@ ruleTester.run('prefer-await-to-then', rule, { code: 'function foo() { hey.finally(x => {}) }', errors: [{ message }], }, + { + code: 'async function hi() { await thing().then() }', + errors: [{ message }], + options: [ + { + strict: true, + }, + ], + }, + { + code: 'async function hi() { await thing().catch() }', + errors: [{ message }], + options: [ + { + strict: true, + }, + ], + }, + { + code: 'async function hi() { await thing().finally() }', + errors: [{ message }], + options: [ + { + strict: true, + }, + ], + }, + { + code: 'function * hi() { yield thing().then() }', + errors: [{ message }], + options: [ + { + strict: true, + }, + ], + }, ], }) diff --git a/docs/rules/prefer-await-to-then.md b/docs/rules/prefer-await-to-then.md index 7fce076a..be9ba170 100644 --- a/docs/rules/prefer-await-to-then.md +++ b/docs/rules/prefer-await-to-then.md @@ -44,3 +44,18 @@ function exampleFour() { return myPromise.finally(cleanup) } ``` + +## Options + +### `strict` + +Normally, this rule allows `then` or `catch` following an `await` (or `yield`) +expression. Setting this option to `true` will err on such cases: + +This will fail with the `strict` option: + +```js +async function hi() { + await thing().then() +} +``` diff --git a/rules/prefer-await-to-then.js b/rules/prefer-await-to-then.js index 0f3de93b..3c2fab76 100644 --- a/rules/prefer-await-to-then.js +++ b/rules/prefer-await-to-then.js @@ -16,7 +16,16 @@ module.exports = { 'Prefer `await` to `then()`/`catch()`/`finally()` for reading Promise values.', url: getDocsUrl('prefer-await-to-then'), }, - schema: [], + schema: [ + { + type: 'object', + properties: { + strict: { + type: 'boolean', + }, + }, + }, + ], messages: { preferAwaitToCallback: 'Prefer await to then()/catch()/finally().', }, @@ -40,9 +49,11 @@ module.exports = { return getScope(context, node).block.type === 'Program' } + const { strict } = context.options[0] || {} + return { 'CallExpression > MemberExpression.callee'(node) { - if (isTopLevelScoped(node) || isInsideYieldOrAwait(node)) { + if (isTopLevelScoped(node) || (!strict && isInsideYieldOrAwait(node))) { return }