Skip to content

Latest commit

 

History

History
86 lines (61 loc) · 3.51 KB

require-await-function.md

File metadata and controls

86 lines (61 loc) · 3.51 KB

Enforce using await with calls to specified functions (square/require-await-function)

💼 This rule is enabled in the 🔥 ember config.

🔧 This rule is automatically fixable by the --fix CLI option.

Some functions are asynchronous and you may want to wait for their code to finish executing before continuing on. The modern async / await syntax can help you achieve this.

Rule Details

This lint rule requires that specified functions be called with the await keyword. The benefits of this include:

  • Ensure code runs in the right (deterministic) order
  • Promote cleaner code by reducing unwieldy promise chain usage
  • Enforce a consistent way of calling/chaining asynchronous functions

Note: this rule does not require using await in return statements or when nested inside other function calls.

Examples

Code sample:

// Lint rule configuration: ['error', { functions: ['asyncFunc1', 'asyncFunc2'] }]
function doSomethingInvalid() {
  // Invalid because specified functions are missing `await`.
  return asyncFunc1().then(() => {
    return asyncFunc2();
  });
}
async function doSomethingValid() {
  await asyncFunc1();
  await asyncFunc2();
}

Here's a code sample demonstrating how it can be especially useful to enforce using the async keyword with asynchronous test action / wait helpers to make tests more deterministic and potentially reduce flakiness.

// Lint rule configuration: ['error', { functions: ['click'] }]
test('clicking the button sends the action', function (assert) {
  click('.my-button'); // Invalid usage.
  assert.ok(this.myAction.calledOnce);
});
test('clicking the button sends the action', function (assert) {
  click('.my-button').then(() => {
    assert.ok(this.myAction.calledOnce);
  }); // Invalid usage.
});
test('clicking the button sends the action', async function (assert) {
  await click('.my-button'); // Valid usage.
  assert.ok(this.myAction.calledOnce);
});

Configuration

This rule accepts a single argument:

  • Set the required functions option to an array of the function names that must be called with await.

Migration

  • async-await-codemod can help convert async function calls / promise chains to use await
  • ember-test-helpers-codemod has transforms such as click that can be modified to call makeAwait() and dropAndThen() on the function calls that you're trying to bring into compliance with this rule

When Not To Use It

You should avoid enabling this rule if:

  • Your JavaScript/browser environment does not support async functions (an ES8/ES2017 feature)
  • You have no asynchronous functions
  • You prefer to use promise chains instead of the async keyword

Related Rules

Resources