promise/prefer-await-to-then

Require await instead of then(), catch() and finally()

A chain of then() callbacks puts each step in its own function, so steps can't share variables, and loops, early returns and try/catch don't work across them. With await, the same code is ordinary statements.

Not reported:

  • the call that a return statement returns, as in return load().then(parse)
  • a chain inside an await or yield expression, unless you set strict
  • a then, catch or finally method on something that clearly isn't a promise, such as an object literal or new Parser()

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"promise/prefer-await-to-then" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"promise/prefer-await-to-then" = ["error", {
  strict = false,
}]

Examples#

example.js2 problems
function showUser(id) {
  fetchUser(id)
    .then(user => render(user))
    .catch(err => showError(err));
}
example.jsNo problems
async function showUser(id) {
  try {
    render(await fetchUser(id));
  } catch (err) {
    showError(err);
  }
}

function loadConfig(path) {
  return readFile(path, "utf8").then(JSON.parse);
}

const parser = new Parser();
parser.then(render);

In a longer chain, return only exempts the last call. Here the then() is reported:

example.js1 problem
function loadConfig(path) {
  return readFile(path, "utf8").then(JSON.parse).catch(useDefaults);
}

Options#

OptionDefaultWhat it does
strictfalseAlso report then(), catch() and finally() inside an await or yield expression.
example.jsNo problems
async function findUser(id) {
  const user = await fetchUser(id).catch(() => null);
  return user ?? guest;
}
example.jswith { "strict": true }1 problem
async function findUser(id) {
  const user = await fetchUser(id).catch(() => null);
  return user ?? guest;
}