promise/no-nesting 风格
它的作用
禁止嵌套的 then() 或 catch() 语句。
为什么这是个问题?
嵌套的 Promise 会使代码更难阅读和理解。
示例
此规则的 错误 代码示例:
javascript
doThing().then(() => a.then());
doThing().then(function () {
a.then();
});
doThing().then(() => {
b.catch();
});
doThing().catch((val) => doSomething(val).catch(errors));此规则的 正确 代码示例:
javascript
doThing().then(() => 4);
doThing().then(function () {
return 4;
});
doThing().catch(() => 4);javascript
doThing()
.then(() => Promise.resolve(1))
.then(() => Promise.resolve(2));此示例不构成规则违规,因为此处解嵌套会导致表达式 getC(a, b) 中的 a 未定义。
javascript
doThing().then((a) => getB(a).then((b) => getC(a, b)));如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["promise"],
"rules": {
"promise/no-nesting": "error"
}
}bash
oxlint --deny promise/no-nesting --promise-plugin