ESLint报prefer-arrow-callback与func-names错误,ES6新手求助改写代码
Fixing ESLint's
prefer-arrow-callback and func-names Errors for Your Server Listen Callback Hey there! Let's break down how to fix those two ESLint errors while keeping your code's logic intact.
First, let's clarify what each error is flagging:
prefer-arrow-callback: ESLint wants you to use arrow functions instead of traditional function expressions for callbacks—they're more concise and avoid unexpectedthisbinding behavior.func-names: This rule bans anonymous functions, requiring all functions to have explicit names (super helpful for debugging stack traces later!).
Your original code uses an anonymous function expression, which triggers both rules:
server.listen(config.site.port, config.site.host, function (err) { if (err) { throw err; } });
Solution: Extract a Named Arrow Function (Recommended)
The cleanest way to satisfy both rules is to define your callback as a named arrow function variable first, then pass it to server.listen:
// Define a named arrow function for the callback const onServerListen = (err) => { if (err) { throw err; } }; // Pass the named function to server.listen server.listen(config.site.port, config.site.host, onServerListen);
If you want to keep things extra concise (without losing readability), you can shorten the error check:
const onServerListen = (err) => { if (err) throw err; }; server.listen(config.site.port, config.site.host, onServerListen);
Why This Works
- The arrow function replaces the old function expression, checking the box for
prefer-arrow-callback. - Naming the function (
onServerListen) fixes thefunc-nameserror, making your code easier to debug when issues pop up.
That's all—your code will now pass both ESLint rules while maintaining its original functionality!
内容的提问来源于stack exchange,提问作者Woppi
相关产品推荐
相关产品推荐

