代码之家  ›  专栏  ›  技术社区  ›  OptimusCrime

使用fetch和TypeScript解码JSON会抛出eslint“预期在箭头函数末尾返回值”错误

  •  0
  • OptimusCrime  · 技术社区  · 4 年前

    我有以下代码尝试执行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));
        });
    }
    

    我已经看过了文档,我很确定这是因为 .then 回调的返回/无返回不一致。我曾尝试对我的代码进行变异,使其要么有回报,要么没有回报,但我一辈子都不知道如何重写这段代码,使eslint再次快乐起来。

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

    然后:

    fetchSomeObject.then((response: SomeResponseType) => {
      [...]
    });
    
    2 回复  |  直到 4 年前
        1
  •  2
  •   CertainPerformance    4 年前

    而你却可以随时修好它 return 调整和调整 .then 从逻辑上讲,最好是 avoid the explicit Promise construction antipattern throw 在它内部停止处理程序并使控制流转到 catch .

    你应该 消费者 fetchJson 接住 在这里,因为当获取失败时,您将返回错误类型的内容—当您 接住 承诺,这在这里是不可取的。

    如果你想 JSON.parse .json() 方法,而不是 .text() 方法,它将自动完成。

    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
        });