Linter · Rules
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
Reported:
function showUser(id) {
fetchUser(id)
.then(user => render(user))
.catch(err => showError(err));
}
Not reported:
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:
function loadConfig(path) {
return readFile(path, "utf8").then(JSON.parse).catch(useDefaults);
}
Options
| Option | Default | What it does |
|---|---|---|
strict | false | Also report then(), catch() and finally() inside an await or yield expression. |
async function findUser(id) {
const user = await fetchUser(id).catch(() => null);
return user ?? guest;
}
async function findUser(id) {
const user = await fetchUser(id).catch(() => null);
return user ?? guest;
}