promise/always-return 의심스러운
해당 규칙의 목적
각 then() 내부에서 반환값을 요구하여 가독성과 재사용이 가능한 프로미스 체인을 만듭니다.
또한 then() 내부에서 예외를 발생시키는 것을 허용하며, 이는 Promise.reject()를 반환하는 것과 사실상 동일합니다.
왜 이 규칙이 중요한가?
끊어진 프로미스 체인. 첫 번째 then() 콜백 내에서 함수가 호출되지만 반환되지 않음.
이로 인해 함수가 완료되기 전에 체인의 다음 then()이 즉시 실행됩니다.
예시
이 규칙에 어긋나는 잘못된 코드 예시:
javascript
myPromise.then(function (val) {});
myPromise.then(() => {
doSomething();
});
myPromise.then((b) => {
if (b) {
return "yes";
} else {
forgotToReturn();
}
});이 규칙을 올바르게 따르는 올바른 코드 예시:
javascript
myPromise.then((val) => val * 2);
myPromise.then(function (val) {
return val * 2;
});
myPromise.then(doSomething); // 둘 중 하나 가능
myPromise.then((b) => {
if (b) {
return "yes";
} else {
return "no";
}
});구성 설정
이 규칙은 다음 속성을 가진 구성 객체를 수락합니다.
ignoreAssignmentVariable
type: string[]
기본값: ["globalThis"]
이 규칙에 { ignoreAssignmentVariable: [] } 옵션을 전달하고 변수 이름 목록을 제공하면,
프로미스 체인의 마지막 then() 콜백이 글로벌 변수에 할당하는 경우 경고하지 않습니다. 기본 값은 ["globalThis"]입니다.
javascript
/* promise/always-return: ["error", { ignoreAssignmentVariable: ["globalThis"] }] */
// OK
promise.then((x) => {
globalThis = x;
});
promise.then((x) => {
globalThis.x = x;
});
// OK
promise.then((x) => {
globalThis.x.y = x;
});
// NG
promise.then((x) => {
anyOtherVariable = x;
});
// NG
promise.then((x) => {
anyOtherVariable.x = x;
});
// NG
promise.then((x) => {
x();
});ignoreLastCallback
type: boolean
기본값: false
이 규칙에 { ignoreLastCallback: true } 옵션을 전달하면,
프로미스 체인의 마지막 then() 콜백이 return 없이도 경고하지 않습니다. 기본 값은 false입니다.
javascript
// OK
promise.then((x) => {
console.log(x);
});
// OK
void promise.then((x) => {
console.log(x);
});
// OK
await promise.then((x) => {
console.log(x);
});
promise
// NG
.then((x) => {
console.log(x);
})
// OK
.then((x) => {
console.log(x);
});
// NG
const v = promise.then((x) => {
console.log(x);
});
// NG
const v = await promise.then((x) => {
console.log(x);
});
function foo() {
// NG
return promise.then((x) => {
console.log(x);
});
}사용 방법
이 규칙을 활성화하려면 구성 파일 또는 CLI를 통해 다음과 같이 사용할 수 있습니다:
json
{
"plugins": ["promise"],
"rules": {
"promise/always-return": "error"
}
}bash
oxlint --deny promise/always-return --promise-plugin