sonarjs/prefer-immediate-return not always a good practice
Poyoman39 opened this issue · comments
I want to report a bug.
Reproducer
const pause = (duration) => new Promise((resolve) => {
setTimeout(resolve, duration);
});
const testThrower = async () => {
await pause(1000);
throw new Error('error test');
};
const fct1 = async () => {
try {
const result = await test();
return result; // sonarjs will advise to immediate return
} catch(e) {
console.log('catched', e);
}
}
const fct2 = async () => {
try {
return test();
} catch(e) {
console.log('catched', e);
}
}
await fct1(); // catched Error: error test
await fct2(); // Uncaught Error: error test
Expected behavior
I think this rule should be disabled, since it may lead to a different behavior, and break error management.
eslint-plugin-sonarjs version: latest
eslint version: latest
Node.js version: LTS
Rule key: sonarjs/prefer-immediate-return
Hello Poyoman39,
Have you considered fixing fct1 as following:
const fct3 = async () => {
try {
return await test();
} catch(e) {
console.log('catched', e);
}
}
We could add this example in the rule definition.
Hello Poyoman39,
Have you considered fixing fct1 as following:
const fct3 = async () => { try { return await test(); } catch(e) { console.log('catched', e); } }We could add this example in the rule definition.
Nice suggestion. In fact fct3 get rejected by eslint base rules, and so maybe it's a problem of this rule : https://eslint.org/docs/latest/rules/no-return-await
eslint: error : return-await - Redundant use of
await on a return value.
From https://eslint.org/docs/latest/rules/no-return-await:
This rule was deprecated in ESLint v8.46.0 with no replacement. The original intent of this rule no longer applies due to the fact JavaScript now handles native Promises differently. It can now be slower to remove await rather than keeping it. More technical information can be found in this V8 blog entry