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
returnstatement returns, as inreturn load().then(parse) - a chain inside an
awaitoryieldexpression, unless you setstrict - a
then,catchorfinallymethod on something that clearly isn't a promise, such as an object literal ornew 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)
.thenPrefer await to then()/catch()/finally()(user => render(user))
.catchPrefer await to then()/catch()/finally()(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").thenPrefer await to then()/catch()/finally()(JSON.parse).catch(useDefaults);
}Options#
| Option | Default | What it does |
|---|---|---|
strict | false | Also 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 problemasync function findUser(id) {
const user = await fetchUser(id).catchPrefer await to then()/catch()/finally()(() => null);
return user ?? guest;
}