You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 unexpected this binding 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; 
  } 
});

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 the func-names error, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:58:19