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

编写返回Promise的函数时,如何解决ESLint与TypeScript ESLint规则冲突

解决ESLint与TypeScript ESLint默认规则冲突的Promise函数写法

项目使用未修改默认规则的ESLint与TypeScript ESLint时,编写返回axios.get调用结果(Promise)的函数会触发规则冲突,以下是问题场景、原因及解决方法:

问题场景

尝试1:直接返回Promise

import { ResponseType } from 'axios'

const getPosts = async (): Promise<ResponseType> => {
  return axios.get("https://jsonplaceholder.typicode.com/posts")
}

触发错误:

Returning an awaited promise is required in this context. eslint(@typescript-eslint/return-await)

尝试2:添加await返回

import { ResponseType } from 'axios'

const getPosts = async (): Promise<ResponseType> => {
  return await axios.get("https://jsonplaceholder.typicode.com/posts")
}

触发错误:

Redundant use of await on a return value. eslint(no-return-await)

尝试3:移除async关键字

触发错误:

Functions that return promises must be async. eslint(@typescript-eslint/promise-function-async)

规则冲突原因

三个规则的核心要求:

  • @typescript-eslint/return-await(默认规则):async函数返回Promise时必须用await,确保Promise的rejection能被async函数捕获并转为rejected Promise
  • no-return-await:禁止在return语句中冗余使用await,因为async函数会自动包装返回值为Promise,直接return Promise和return await Promise行为几乎一致(除try/catch场景)
  • @typescript-eslint/promise-function-async:返回Promise的函数必须标记为async

解决方案

方案1:用try/catch包裹,让await不再冗余

通过添加try/catch块,await就不再是冗余的——它能捕获axios.get的rejection,符合所有规则要求:

import { ResponseType } from 'axios'

const getPosts = async (): Promise<ResponseType> => {
  try {
    return await axios.get("https://jsonplaceholder.typicode.com/posts")
  } catch (error) {
    // 可在此处理错误,或直接重新抛出
    throw error
  }
}

方案2:调整规则配置(允许修改规则时)

如果项目允许调整ESLint规则,可修改配置解决冲突:

  • 将@typescript-eslint/return-await设置为"in-try-catch":仅要求在try/catch块中返回Promise时用await,其他场景允许直接return Promise
  • 或者关闭no-return-await规则,因为@typescript-eslint/return-await已覆盖更严格的校验场景

核心规则说明

  • no-return-await:禁止return语句中对Promise用冗余await,async函数会自动包装返回值为Promise,冗余await无意义(仅在try/catch中是必要的,用于捕获错误)
  • @typescript-eslint/return-await:默认要求async函数返回Promise必须用await,确保rejection能被正确转化为async函数的rejected Promise;支持always(默认)和in-try-catch两个选项

内容的提问来源于stack exchange,提问作者MalwareMoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:57:09