使用 Typescript 为 json 流重写对双簧管的提取调用

Rewrite fetch call to oboe for json streams with Typescript

我有这个提取调用:

 api<T>(url: string, headers: Request): Promise<T> {
        return fetch(url, headers)
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json().then(data => data as T);
            })
            .catch((error: Error) => {
                throw error;
            });
    }
    componentDidMount(){
        this.api<Array<Response>>(url, requestData)
            .then(data  => {
                this.setState({
                    jobs: data
                });
            })
            .catch(error => {
                console.error(error);
            });
    }

但是我得到的响应是一个流+json,所以我在 .json().

处无效 json

我看到有一个图书馆可以帮助我:http://oboejs.com/examples

但我在使用双簧管和打字稿时遇到问题(初学者)(使用 https://www.npmjs.com/package/@types/oboe)。

我试过了:

api<T>(headers: Request): Oboe<T> {
        return oboe(headers)
            .done(function(response) {
                return response;
            })
            .fail(function(error: Error) {
                throw error;
            });
    }
    componentDidMount(){
        this.api<Array<Response>>(requestData)
            .done(data  => {
                this.setState({
                    jobs: data
                });
            })
            .fail(error => {
                console.error(error);
            });
    }

但是有明显的错误,因为我不知道双簧管应该是什么类型 return 所以我得到一个错误 Oboe is not generic.

  • 错误意味着 Oboe class/type 不是通用的。例如 StringNumber
  • Oboe's docs看来oboe(param).done()需要回调
  • 您可以将该调用转换为 Promise,然后按照与以往相同的方式进行其余操作

Promise

替换回调逻辑
api<T>(headers: Request): Promise<T> {
  return new Promise((resolve, reject) => {
    oboe(headers)
      .done(data => resolve(data))
      .fail(err => reject(err));
  });
}

调用它(用 Promise/fetch 的方式)

componentDidMount(){
    this.api<Array<Response>>(url, requestData)
        .then(data  => {
            this.setState({
                jobs: data
            });
        })
        .catch(error => {
            console.error(error);
        });
}