【问题标题】:Decoding JSON with fetch and TypeScript throws eslint "Expected to return a value at the end of arrow function" error使用 fetch 和 TypeScript 解码 JSON 会引发 eslint“预期在箭头函数末尾返回值”错误
【发布时间】:2020-04-28 22:15:31
【问题描述】:

我有以下代码尝试执行 AJAX 请求,然后在一直保持类型的同时解码有效负载:

export function fetchJson<T>(url: string, data: FetchDataTypes): Promise<T> {
    return new Promise((resolve, reject) => {
        fetch(url, {})
            .then((response: Response) => {
                if (!response.ok) {
                    reject(response);
                } else {
                    return response.text() as Promise<string>;
                }
            })
            .then((text: string) => {
                try {
                    resolve(JSON.parse(text) as T);
                } catch (err) {
                    reject(err);
                }
            })
            .catch((err: Promise<void>) => reject(err));
    });
}

问题是eslint抛出这个错误:

期望在箭头函数consistent-return结束时返回一个值

我查看了文档,我很确定这是因为第一个 .then 回调在返回/不返回方面存在不一致。我试图改变我的代码,要么有回报,要么没有回报,但我一生都无法弄清楚如何重写这段代码以让 eslint 再次快乐。

我能找到的所有相关问题都是开发人员忘记从映射器方法等返回的错误,而我找不到与我的场景相关的错误。

编辑:为了清楚起见,我希望能够像这样调用我的函数:

export const fetchSomeObject = (): Promise<SomeResponseType> =>
  fetchJson('/api/some-endpoint', {
    method: 'GET',
    headers: {},
  });

然后:

fetchSomeObject.then((response: SomeResponseType) => {
  [...]
});

【问题讨论】:

    标签: typescript eslint


    【解决方案1】:

    虽然您可以通过始终 returning 并调整 .then 逻辑来解决它,但完全使用 avoid the explicit Promise construction antipattern 会更好,完全回避这个问题。当 Promise 出现错误时,您可以在其中 throw 停止处理程序并使控制流转到 catch

    你应该在fetchJsonconsumercatch - 不要在这里catch,因为那样,当获取失败时,你将返回错误类型的东西 -当你catch 时,你返回一个 resolved Promise,这在这里是不可取的。

    如果您想JSON.parse 回复,请使用.json() 方法,而不是.text() 方法,它会自动完成。

    另请注意,当 TS 已经可以推断出类型时,无需显式注明类型。

    export function fetchJson<T>(url: string): Promise<T> {
        return fetch(url)
            .then((response) => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                } else {
                    return response.json();
                }
            });
    }
    
    // Then in the consumer:
    fetchJson<someType>('someURL')
        .then((result) => {
            // result is of type someType
        })
        .catch((err) => {
            // handle errors here
        });
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多